[英]Regex that recognizes ^^ and ^ as different
I am using the Python re
module. 我正在使用Python re
模块。
I can use the regex r'\\bA\\b'
(a raw string) to differentiate between 'A'
and 'AA'
: it will find a match in the string 'A'
and no matches in the string 'AA'
. 我可以使用正则表达式r'\\bA\\b'
(原始字符串)来区分'A'
和'AA'
:它将在字符串'A'
找到匹配项,而在字符串'AA'
找不到匹配项。
I would like to achieve the same thing with a carat ^
instead of the A
: I want a regex which differentiates between '^'
and '^^'
. 我想用克拉^
而不是A
来实现相同的目的:我想要一个区分'^'
和'^^'
的正则表达式。
The problem I have is that the regex r'\\b\\^\\b'
does not find a match in '^
'. 我的问题是正则表达式r'\\b\\^\\b'
在'^
'中找不到匹配项。
Any ideas? 有任何想法吗?
You need to use lookaround for this: 您需要为此使用环顾:
(?<!\^)\^(?!\^)
\\b
is a word boundary, a place between a word character and a non-word character, so your pattern is quite non-specific (doesn't say anything about A
specifically, A_
would also not match given that _
is a word character. \\b
是一个单词边界,介于一个单词字符和一个非单词字符之间,因此您的模式是非常不特定的(关于A
并没有特别说明,鉴于_
是单词字符, A_
也不会匹配。
Here, we assert that there needs to be a place where the preceding character is not a caret, then a caret, then a place where the following character is not a caret (which boils down to "the caret must not be in caret company"). 在这里,我们断言必须存在一个前面字符不是插入符号的地方,然后是插入符号,然后是后面字符不是插入符号的地方(归结为“插入符号一定不能在插入符号中”)。 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.