没有一个案例的正则表达式模式

sie*_*ema 3 regex bash grep sed

我想从文件名中删除一些字符串.我想删除括号中的每个字符串但是如果有字符串"remix"或"Remix"或"REMIX"则不会删除现在我有了

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

但如果在字符串中有混音时如何排除案例?

Cas*_*yte 5

您可以使用捕获组:

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

当"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. ]*)
Run Code Online (Sandbox Code Playgroud)

\1 是对捕获组1的引用

i 使模式不区分大小写

[编辑]

如果要以符合POSIX的方式进行,则必须使用不同的方法,因为几个Gnu功能不可用,特别是交替\|(还有i修饰符,\s字符类,可选的量词\?).

另一种方法是找到所有不是左括号的最终字符,并且括号内的所有最终子字符串都包含在内部的"remix"中,后跟最终的空格和括号之间的最终子字符串.

正如您所看到的,all是可选的,模式可以匹配空字符串,但这不是问题.

在组1中捕获要删除的括号部分之前的所有部分.

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

图案细节:

\(     # 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)
Run Code Online (Sandbox Code Playgroud)

此模式中的单词边界也不可用.因此,模仿它们的唯一方法是列出四种可能性:

([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
Run Code Online (Sandbox Code Playgroud)

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

\(poss1\)\{0,\}\(poss2\)\{0,\}\(poss3\)\{0,\}\(poss4\)\{0,\}
Run Code Online (Sandbox Code Playgroud)