我有一个像下面的字符串
let value : '<ns2:NewsPaper unitid="112345">
<idType>DG</idType>
</ns2:NewsPaper>'
我需要<ns2:NewsPaper.
的内容我写了一段代码。但它返回null。这是我的代码:
let abc = /NewsPaper>(\*)</.exec(value);
console.log(abc);
它返回null。为什么?
一种更简单的匹配方式是:
let rex = /unitid=\"\d*\"/g;
let abc = rex.exec(value); // ["unitid="112234"", "unitid="112234""]
这个正则表达式应该适用于您正在抓取的内容:
unitid="[^"]+"
它将字面上匹配unitid="
,角色的角色。然后它将匹配[^"]
至于JS这样:
const value = '<ns2:NewsPaper unitid="112234">';
const regex = /unitid="[^"]+?"/;
const matches = value.match(regex);
console.log(matches);
// => ["unitid=\"112234\""]
注意如何捕获parens是不必要的。这是因为JS实现了match(..)
函数。包含捕获parens时的输出将是:
["unitid=\"112234\"", "unitid=\"112234\""]
即使您使用exec(..)
函数,您也应该期望这种行为。因此,在某些情况下,可能需要省略捕获的parens。 matches
数组的第一个元素将是你的正则表达式消耗的任何元素;第一个元素后面的所有内容都是正则表达式捕获的项目。