gpt4 book ai didi

regex - 类似 Perl 的速记字符类在括号表达式中不起作用

转载 作者:行者123 更新时间:2023-12-04 13:23:17 25 4
gpt4 key购买 nike

\s 似乎不适用于

sed 's/[\s]\+//' tempfile

当它为

工作时
sed 's/[ ]\+//' tempfile

我正在尝试删除由于命令而出现在每行开头的空格:

nl -s ') ' file > tempfile  

例如文件:

A Storm of Swords, George R. R. Martin, 1216
The Two Towers, J. R. R. Tolkien, 352
The Alchemist, Paulo Coelho, 197
The Fellowship of the Ring, J. R. R. Tolkien, 432
The Pilgrimage, Paulo Coelho, 288
A Game of Thrones, George R. R. Martin, 864

临时文件:

 1) Storm of Sword, George R. R. Martin, 1216
2) The Two Tower, J. R. R. Tolkien, 352
3) The Alchemit, Paulo Coelho, 197
4) The Fellowhip of the Ring, J. R. R. Tolkien, 432
5) The Pilgrimage, Paulo Coelho, 288
6) A Game of Throne, George R. R. Martin, 864

即数字前有空格

请解释为什么会出现空格以及 \s 不起作用的原因。

最佳答案

原因很简单:POSIX 正则表达式引擎不解析括号表达式内的类似 Perl 的速记字符类。

参见 this reference :

One key syntactic difference is that the backslash is NOT a metacharacter in a POSIX bracket expression. So in POSIX, the regular expression [\d] matches a \ or a d.

所以,[\s]在 POSIX 正则表达式中匹配两个符号之一:\s .

考虑 following demo :

echo 'ab\sc' | sed 's/[\s]\+//'

输出为 abc . \s子字符串被删除。

考虑使用 POSIX 字符类而不是类似 Perl 的简写:

echo 'ab\s c' | sed 's/[[:space:]]\+//'

参见 this online demo (输出为 ab\sc )。 POSIX 字符类由 [:<NAME_OF_CLASS>:] 组成, 它们只能在方括号表达式中使用。参见 more examples of POSIX character classes here .

注意:如果要确保删除行首的空格,请添加 ^在模式开始处:

sed 's/^[[:space:]]\+//'
^

更多模式:

  • \w = [[:alnum:]_]
  • \W = [^[:alnum:]_]
  • \d = [[:digit:]] (或 [0-9] )
  • \D = [^[:digit:]] (或 [^0-9] )
  • \h = [[:blank:]]
  • \S = [^[:space:]]

关于regex - 类似 Perl 的速记字符类在括号表达式中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46020936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com