【问题标题】:Sed regexp looking for either whitespace or end of lineSed 正则表达式寻找空格或行尾
【发布时间】:2013-01-02 23:43:09
【问题描述】:

我正在尝试检测包含三个部分的模式:

  1. 一个空间
  2. “m”或“t”
  3. 空格或行尾

我想保留#2 和#3。例如,我想将“我确定他不会”更改为“我确定他不会”

我无法表达 #3,因为 [ $] 似乎只匹配空格,而不是行尾。这是我尝试过的:

$ echo "i m sure he doesn t" | sed 's/ \([mt]\)\([ $]\)/\1\2/g'
im sure he doesn t

我应该如何在上面的表达式中表达“空格或行尾”?谢谢!

【问题讨论】:

  • 一旦将$ 放入[] 中,它就会被视为字面意思,而不是行尾标记

标签: regex sed


【解决方案1】:

空格还是行尾?使用|:

s/ \([mt]\)\( \|$\)/\1\2/g

【讨论】:

  • 这个对我不起作用。它仍然忽略行尾。 $ echo "i m sure he doesn t" | sed 's/ \([mt]\)\( \|$\)/\1\2/' im sure he doesn t
  • 是否有不同风格的 unix 或 sed 会给我带来不同的结果?如果是这样,我如何确定我使用的是哪一个?
  • @Moira:只需在末尾添加/g
【解决方案2】:

仅匹配空格,然后是 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.

【讨论】:

  • 完美!我不在 Mac 上,所以这对我有用:sed 's/ \([mt]\)\>/\1/g'
【解决方案3】:

最后一个空格是可选的:

sed 's/[ ]\([mt][ ]\?\)$/\1/' input

Posix 友好版本:

sed 's/[ ]\([mt][ ]\{,1\}\)$/\1/' input

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多