Emacs正则表达式:什么\<和\>可以做到吗? [英] Emacs regular expression: what \< and \> can do that \b cannot do?
问题描述
正则表达式反斜杠 - GNU Emacs手册说 \<
在单词开头匹配, \>
单词和 \b
匹配单词边界。 \b
与其他非Emacs正则表达式一样。但是,对于Emacs正则表达式来说,似乎 \<
和 \>
是特别的。是否需要 \<
和 \>
,而不是 \\ \\b
?例如, \bword\b
将与 \< word\>
将匹配,唯一的区别是后者更可读。
Regexp Backslash - GNU Emacs Manual says that \<
matches at the beginning of a word, \>
matches at the end of a word, and \b
matches a word boundary. \b
is just as in other non-Emacs regular expressions. But it seems that \<
and \>
are particular to Emacs regular expressions. Are there cases where \<
and \>
are needed instead of \b
? For instance, \bword\b
would match the same as \<word\>
would, and the only difference is that the latter is more readable.
推荐答案
如果您假设他们的行为相同,您可以获得意想不到的结果..
什么可以\<和> \可以做什么?
答案是 \<
和 \>
是显式 ...这个结尾!只有这个目的!
\b
是一般 ....一个单词的末尾都会匹配.. 。
You can get unexpected results if you assume they behave the same..
What can \< and > that \b can do?
The answer is that \<
and\>
are explicit... This end of a word! and only this end!
\b
is general.... Either end of a word will match...
GNU运算符* Word Operators
line="cat dog sky"
echo "$line" |sed -n "s/\(.*\)\b\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\>\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\<\(.*\)/# |\1|\2|/p"
echo
line="cat dog sky"
echo "$line" |sed -n "s/\(.*\)\b\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\>\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\<\(.*\)/# |\1|\2|/p"
echo
line="cat dog sky "
echo "$line" |sed -n "s/\(.*\)\b\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\>\(.*\)/# |\1|\2|/p"
echo "$line" |sed -n "s/\(.*\)\<\(.*\)/# |\1|\2|/p"
echo
输出
# |cat dog |sky|
# |cat dog| sky|
# |cat dog |sky|
# |cat dog |sky|
# |cat dog| sky|
# |cat dog |sky|
# |cat dog sky| |
# |cat dog sky| |
# |cat dog |sky |
这篇关于Emacs正则表达式:什么\<和\>可以做到吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!