gpt4 book ai didi

正则表达式:负后视和否定之间的区别

转载 作者:行者123 更新时间:2023-12-01 09:27:04 25 4
gpt4 key购买 nike

来自 regular-expressions.info :

\b\w+(?<!s)\b. This is definitely not the same as \b\w+[^s]\b. When applied to Jon's, the former will match Jon and the latter Jon' (including the apostrophe). I will leave it up to you to figure out why. (Hint: \b matches between the apostrophe and the s). The latter will also not match single-letter words like "a" or "I".

你能解释一下为什么吗?

另外,你能说清楚具体是什么\b吗?确实如此,以及为什么它在撇号和 s 之间匹配?

最佳答案

\b是一个零宽度断言,表示 word boundary .这些字符位置(取自该链接)被视为单词边界:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

单词字符当然是任何\w . s是一个单词字符,但是 '不是。在上面的例子中,' 之间的区域和 s是单词边界。

字符串 "Jon's"如果我突出显示 anchor 和边界,看起来像这样(第一个和最后一个 \b 出现在与 ^$ 相同的位置): ^Jon\b'\bs$

否定的后向断言 (?<!s)\b意味着它只会匹配一个单词边界,如果它前面没有字母s (即最后一个单词字符不是 s )。所以它在一定的条件下寻找一个词的边界。

因此第一个正则表达式的工作方式如下:

  1. \b\w+匹配前三个字母 J o n .

  2. n 之间实际上还有另一个单词边界。和 '如上图,所以(?<!s)\b匹配这个词的边界,因为它前面有一个 n ,而不是 s .

  3. 由于已经到达模式的末尾,结果匹配是Jon .

互补字符类[^s]\b表示它将匹配 任何不是字母 s 的字符,后跟单词边界。与上面不同的是,这会查找一个字符后跟一个单词边界。

因此,第二个正则表达式的工作方式如下:

  1. \b\w+匹配前三个字母 J o n .

  2. 自从'不是字母s (它满足字符类 [^s] ),并且后跟一个单词边界(在 's 之间),它是匹配的。

  3. 由于已经到达模式的末尾,结果匹配是Jon' .信s 匹配,因为它之前的单词边界已经匹配。

关于正则表达式:负后视和否定之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7281649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com