我正在尝试检测包含三个部分的模式:
我想保留#2 和#3。例如,我想将“我确定他没有”更改为“我确定他没有”
我在表达 #3 时遇到了麻烦,因为
[ $]
似乎只匹配空格,而不是行尾。这是我尝试过的:$ echo "i m sure he doesn t" | sed 's/ \([mt]\)\([ $]\)/\1\2/g'
im sure he doesn t
我应该如何在上面的表达式中表达“空格或行尾”?谢谢!
最佳答案
仅匹配空格,然后是 m 或 t,然后是空格或换行符不会捕获带有标点符号的情况,例如'
中缺少 "please don t!"
。更通用的解决方案是使用单词边界代替:
echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
OS X(我使用的)上需要时髦的
[[:>:]]
,请参阅 Larry Gerndt 对 sed whole word search and replace 的回答。在其他 sed 版本上,您可以改用 \b
(任何单词边界)或 \>
。# example with word boundary
echo "i m sure he doesn t test test don t." | sed 's/ \([mt]\)[[:>:]]/\1/g'
im sure he doesnt test test dont.
关于regex - Sed regexp 寻找空白或行尾,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14131020/