javascript多行匹配在某个字符串之后

javascript multiline match after a certain string

本文关键字:字符串 之后 javascript      更新时间:2023-09-26

在此文本中:

my-Word: Value-1
othertext
my-Word: Value-2
othertext
my-Word: Value-3
...

我需要匹配包含以下内容的所有字符串:([A-Za-z0-9-]+)

并且仅在字符串之后:my-Word:,但不包括:my-Word:

所以我只需要匹配:Value-1Value-2Value-3

我该怎么做?

您可以使用正向查找:

(?<=my-Word:'s*)([A-Za-z0-9-]+)

使用捕获组捕获my-Word: 之后出现的字母数字字符

> var s = "my-Word: Value-1'nothertext'nmy-Word: Value-2'nothertext'nmy-Word: Value-3"
undefined
> var re = /my-Word:'s*([A-Za-z0-9-]+)/gm;
undefined
> var m;
undefined
> while ((m = re.exec(s)) != null) {
... console.log(m[1]);
... }
Value-1
Value-2
Value-3

您必须使用lookbacking正则表达式,例如:

.(?<=my-Word: [A-Za-z0-9-])[A-Za-z0-9-]+

但不幸的是,javascript不支持lookbacking,因此您可以使用lookahead正则表达式。为此,您需要首先反转原始字符串,最后匹配部分:

[A-Za-z0-9-]+(?= :droW-ym)

演示