字边界结束和边缘之间的正则表达式差异 [英] Regex difference between word boundary end and edge

查看:63
本文介绍了字边界结束和边缘之间的正则表达式差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式

符号\<和 \> 分别匹配在一个词的开头和结尾.符号 \b 匹配空字符串一个字的边缘

The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word

(一个词的)结束和边缘有什么区别?

What is the difference between an end and an edge (of a word)?

推荐答案

\b\</\> 的区别code> 是 \b 可用于 PCRE 正则表达式模式(当您指定 perl=TRUE 时)和 ICU 正则表达式模式(stringr 包).

The difference between the \b and \< / \> is that \b can be used in PCRE regex patterns (when you specify perl=TRUE) and ICU regex patterns (stringr package).

> s = "no where nowhere"
> sub("\\<no\\>", "", s)
[1] " where nowhere"
> sub("\\<no\\>", "", s, perl=T) ## \> and \< do not work with PCRE
[1] "no where nowhere"
> sub("\\bno\\b", "", s, perl=T) ## \b works with PCRE
[1] " where nowhere"

> library(stringr)
> str_replace(s, "\\bno\\b", "")
[1] " where nowhere"
> str_replace(s, "\\<no\\>", "")
[1] "no where nowhere"

\<(始终代表单词的开头)和 \>(始终匹配单词的结尾)的优点在于它们是明确的.\b 可以匹配两个位置.

The advantage of \< (always stands for the beginning of a word) and \> (always matches the end of a word) is that they are unambiguous. The \b may match both positions.

还有一件事要考虑(参考):

One more thing to consider (refrence):

gsub 和 gregexpr 的 POSIX 1003.2 模式对于重复的字边界(例如,pattern = "\b")无法正常工作.将 perl = TRUE 用于此类匹配(但对于非 ASCII 输入可能无法按预期工作,因为单词"的含义取决于系统).

POSIX 1003.2 mode of gsub and gregexpr does not work correctly with repeated word-boundaries (e.g., pattern = "\b"). Use perl = TRUE for such matches (but that may not work as expected with non-ASCII inputs, as the meaning of ‘word’ is system-dependent).

这篇关于字边界结束和边缘之间的正则表达式差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆