如何不匹配一个单词的最后一个字符?

时间:2021-10-14 20:49:18

I am trying to create a regex that does not match a word (a-z only) if the word has a : on the end but otherwise matches it. However, this word is in the middle of a larger regex and so I (don't think) you can use a negative lookbehind and the $ metacharacter.

我正在尝试创建一个不匹配一个单词(仅a-z)的regex,如果这个单词的末尾有一个:,但在其他方面与它匹配。但是,这个词在一个较大的regex中,所以我(不认为)您可以使用一个负面的lookbehind和$ metacharacter。

I tried this negative lookahead instead:

我尝试了这种消极的展望:

([a-z]+)(?!:)

but this test case

但是这个测试用例

example:

just matches to

只是比赛

exampl

instead of failing.

而不是失败。

4 个解决方案

#1


4  

If you are using a negative lookahead, you could put it at the beginning:

如果你使用的是负面展望,你可以把它放在开头:

(?![a-z]*:)[a-z]+

i.e: "match at least one a-z char, except if the following chars are 0 to n 'a-z' followed by a ':'"

我。e:“匹配至少一个a-z字符,除非下面的字符是0到n 'a-z',然后是':'”。

That would support a larger regex:

这将支持更大的regex:

 X(?![a-z]*:)[a-z]+Y

would match in the following string:

将匹配为以下字符串:

 Xeee Xrrr:Y XzzzY XfffZ

only 'XyyyY'

只有“XyyyY”

#2


0  

Try this:

试试这个:

[a-z]\s

#3


0  

([a-z]+\b)(?!:)

asserts a word boundary at the end of the match and thus will fail "exampl"

在匹配结束时断言单词边界,因此将失败“exampl”

#4


0  

[a-z]+(?![:a-z])

[a - z]+(? ![a - z]):

#1


4  

If you are using a negative lookahead, you could put it at the beginning:

如果你使用的是负面展望,你可以把它放在开头:

(?![a-z]*:)[a-z]+

i.e: "match at least one a-z char, except if the following chars are 0 to n 'a-z' followed by a ':'"

我。e:“匹配至少一个a-z字符,除非下面的字符是0到n 'a-z',然后是':'”。

That would support a larger regex:

这将支持更大的regex:

 X(?![a-z]*:)[a-z]+Y

would match in the following string:

将匹配为以下字符串:

 Xeee Xrrr:Y XzzzY XfffZ

only 'XyyyY'

只有“XyyyY”

#2


0  

Try this:

试试这个:

[a-z]\s

#3


0  

([a-z]+\b)(?!:)

asserts a word boundary at the end of the match and thus will fail "exampl"

在匹配结束时断言单词边界,因此将失败“exampl”

#4


0  

[a-z]+(?![:a-z])

[a - z]+(? ![a - z]):