gpt4 book ai didi

没有一种情况的正则表达式模式

转载 作者:行者123 更新时间:2023-11-29 09:21:29 25 4
gpt4 key购买 nike

我想从文件名中删除一些字符串。我想删除括号中的每个字符串,但如果有字符串“remix”或“Remix”或“REMIX”则不删除现在我有

sed "s/\s*\(\s?[A-z0-9.]*\)//g"

但是如何排除字符串中有remix的情况呢?

最佳答案

您可以使用捕获组:

sed 's/\(\s*([^)]*remix[^)]*)\)\|\s*(\s\?[a-z0-9. ]*)/\1/gi'

当“remix branch”不匹配时,不定义捕获组,匹配部分替换为空字符串。

当“remix branch”成功时,匹配的部分被捕获组的内容替换,所以被它自己替换。

注意:如果这有助于避免误报,您可以在“remix”周围添加单词边界:\bremix\b

图案细节:

\(           # open the capture group 1
\s* # zero or more white-spaces
( # a literal parenthesis
[^)]* # zero or more characters that are not a closing parenthesis
remix
[^)]*
)
\) # close the capture group 1
\| # OR
# something else between parenthesis

\s* # note that it is essential that the two branches are able to
# start at the same position. If you remove \s* in the first
# branch, the second branch will always win when there's a space
# before the opening parenthesis.
(\s\?[a-z0-9. ]*)

\1 是对捕获组 1 的引用

i 使模式不区分大小写

[编辑]

如果你想以符合 POSIX 的方式来做,你必须使用不同的方法,因为有几个 Gnu 特性不可用,特别是交替 \|(还有 i 修饰符,\s 字符类,可选量词 \?)。

另一种方法是查找所有不是左括号的最终字符和包含在括号之间的所有最终子字符串,其中包含“remix”,后跟最终的空格和包含在括号之间的最终子字符串.

如您所见,所有内容都是可选的,模式可以匹配空字符串,但这不是问题。

要删除的括号部分之前的所有内容都在第 1 组中捕获。

sed 's/\(\([^(]*([^)]*[Rr][Ee][Mm][Ii][Xx][^)]*)[^ \t(]*\([ \t]\{1,\}[^ \t(]\{1,\}\)*\)*\)\([ \t]*([^)]*)\)\{0,1\}/\1/g;'

图案细节:

\(     # open the capture group 1
\(
[^(]* # all that is not an opening parenthesis
# substring enclosed between parenthesis without "remix"
( [^)]* [Rr][Ee][Mm][Ii][Xx] [^)]* )

# Let's reach the next parenthesis without to match the white-spaces
# before it (otherwise the leading white-spaces are not removed)
[^ \t(]* # all that is not a white-space or an opening parenthesis
# eventual groups of white-spaces followed by characters that are
# not white-spaces nor opening parenthesis
\( [ \t]\{1,\} [^ \t(]\{1,\} \)*
\)*
\) # close the capture group 1
\(
[ \t]* # leading white-spaces
([^)]*) # parenthesis
\)\{0,1\} # makes this part optional (this avoid to remove a "remix" part
# alone at the end of the string)

此模式下的单词边界也不可用。所以模仿它们的唯一方法是列出四种可能性:

([Rr][Ee][Mm][Ii][Xx])                # poss1
([Rr][Ee][Mm][Ii][Xx][^a-zA-Z][^)]*) # poss2
([^)]*[^a-zA-Z][Rr][Ee][Mm][Ii][Xx]) # poss3
([^)]*[^a-zA-Z][Rr][Ee][Mm][Ii][Xx][^a-zA-Z][^)]*) # poss4

并将 ([^)]*[Rr][Ee][Mm][Ii][Xx][^)]*) 替换为:

\(poss1\)\{0,\}\(poss2\)\{0,\}\(poss3\)\{0,\}\(poss4\)\{0,\}

关于没有一种情况的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30697763/

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