正则表达式,使用正则表达式从多行中查找与A23 Z 12345
完全相同的文本。如果发现以上结果,则为TRUE。
输入:
For the following policy A23 Z 12345 will be cancelled.
预期输出:
A23 Z 12345
答案 0 :(得分:1)
精确捕获的表达非常简单。您可能只想在其周围添加一个捕获组而没有任何其他边界,它会这样做:
(A23 Z 12345)
如果愿意,可以使用this tool测试/编辑/更新/更改该表达式。如果需要,可以为其添加更多边界。
此图显示了表达式的工作方式,您可以在此link中可视化其他表达式:
const regex = /(A23 Z 12345)/gm;
const str = `Any other chars that might be A23 Z 12345 and any other chars after A23 Z 12345 Any other chars that might be A23 Z 12345 and any other chars after A23 Z 12345 Any other chars that might be A23 Z 12345 and any other chars after A23 Z 12345 `;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
此JavaScript代码段使用简单的100万次for
循环来显示该表达式的性能。
const repeat = 1000000;
const start = Date.now();
for (var i = repeat; i >= 0; i--) {
const string = 'Any other chars that might be A23 Z 12345 and any other chars after';
const regex = /(.*)(A23 Z 12345)(.*)/gm;
var match = string.replace(regex, "$2");
}
const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ");
答案 1 :(得分:0)
使用re库解决此问题的Python解决方案:
x = 'For the following policy A23 Z 12345 will be cancelled. A23 Z 123456r will be cancelled.'
print(re.findall('A23 Z 12345', x))
['A23 Z 12345', 'A23 Z 12345']