为什么行尾 (\\b) 在 stringr/ICU 和 Perl 中不被识别为单词边界

Why does is this end of line (\\b) not recognised as word boundary in stringr/ICU and Perl

使用 stringr 我尝试检测字符串末尾的 符号,如下所示:

str_detect("my text €", "€\b") # FALSE

为什么这不起作用?它适用于以下情况:

str_detect("my text a", "a\b") # TRUE - letter instead of €
grepl("€\b", "2009in €") # TRUE - base R solution

但它在 perl 模式下也失败了:

grepl("€\b", "2009in €", perl=TRUE) # FALSE

那么 €\b-regex 有什么问题呢?正则表达式 €$ 在所有情况下都有效...

\b

相当于

(?:(?<!\w)(?=\w)|(?<=\w)(?!\w))

也就是说匹配

  • 在单词字符和非单词字符之间,
  • 在单词字符和字符串开头之间,并且
  • 在字符字符和字符串结尾之间。

是符号,符号不是文字。

$ uniprops €
U+20AC <€> \N{EURO SIGN}
    \pS \p{Sc}
    All Any Assigned Common Zyyy Currency_Symbol Sc Currency_Symbols S Gr_Base Grapheme_Base Graph X_POSIX_Graph GrBase Print X_POSIX_Print Symbol Unicode

如果您的语言支持后视和前视,您可以使用以下内容找到 space 和非 space 之间的边界(将开始和结束视为 space).

(?:(?<!\S)(?=\S)|(?<=\S)(?!\S))

当您使用不带 perl=TRUE 的基本 R 正则表达式函数时,将使用 TRE regex flavor

看来TRE词界:

  • 在非单词字符匹配字符串结束位置后使用,并且
  • 在非单词字符匹配字符串开始位置之前使用。

查看 R 测试:

> gsub("\b\)", "HERE", ") 2009in )")
[1] "HERE 2009in )"
> gsub("\)\b", "HERE", ") 2009in )")
[1] ") 2009in HERE"
> 

这不是 word boundary 在 PCRE 和 ICU 正则表达式风格中的常见行为,其中非单词字符之前的单词边界仅在字符前面带有单词 char 时才匹配,不包括开头字符串位置(并且在非单词字符之后使用时需要单词字符出现在单词边界之后):

There are three different positions that qualify as word boundaries:

- 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.