如何使用正则表达式Java替换方括号内的下划线

时间:2022-12-01 21:42:51

I am trying to replace dashes within the square brackets with underscores but it replaces all dashes with underscores in string.

我试图用下划线替换方括号内的破折号,但它用字符串中的下划线替换所有破折号。

For example, I want to replace

例如,我想要替换

"[a]-[a-gamma]"

with

"[a]-[a_gamma]"

but it replaces all dashes from the string with underscores.

但它用下划线替换字符串中的所有破折号。

5 个解决方案

#1


You can use

您可以使用

String n="[a]-[a-gamma]";
System.out.println(n.replaceAll("-(?=[^\\[\\]]*\\])", "_"));

As for the regex itself, I match the - symbol only if it is followed by non-[s and non-]s until the engine finds the ]. Then, we are "inside" the []s. There can be a situation when this is not quite true (4th hyphen in [a-z]-[a-z] - ] [a-z]), but I hope it is not your case.

至于正则表达式本身,我只匹配 - 符号,如果它后跟非[s和非] s,直到引擎找到]。然后,我们在[] s里面。可能存在这种情况并非如此([a-z] - [a-z] - ] [a-z]中的第4个连字符),但我希望不是你的情况。

IDEONE Demo

Output:

[a]-[a_gamma]

#2


-(?=[^\\[]*\\])

You can use this.See demo.

你可以使用它。参见演示。

https://regex101.com/r/bN8dL3/6

#3


Use a negative lookahead:

使用否定前瞻:

str = str.replaceAll("-(?![^\\]]*\\[)", "_");

The regex matches dashes whose next square bracket character is not an opening square bracket.

正则表达式匹配破折号,其下一个方括号字符不是左方括号。

#4


If your brackets are balanced (or if an unclosed bracket is considered opened by default until the end), you can use this way that needs few steps to find a match:

如果您的括号是平衡的(或者如果默认情况下将未关闭的括号打开直到结束),您可以使用这种方式来找到匹配项:

pattern:

((?:\\G(?!\\A)|[^\\[]*\\[)[^\\]-]*)-

replacement:

$1_

demo

pattern details:

(                   # open the capture group 1
    (?:             # open a non capturing group for the 2 possible beginings
        \\G (?!\\A) # this one succeeds immediately after the last match
      |
        [^\\[]* \\[ # this one reach the first opening bracket
                    # (so it is the first match)
    )
    [^\\]-]*        # all that is not a closing bracket or a dash
)                   # close the capture group
-                   # the dash

The \G anchor marks the position after the last match. But at the begining (since there isn't already a match), it matches by default the start of the string. This is the reason why I added (?!\A) to fail at the start of the string.

\ G锚标记最后一场比赛后的位置。但是在开始时(因为还没有匹配),它默认匹配字符串的开头。这就是我在字符串开头添加(?!\ A)失败的原因。

#5


How about this?

这个怎么样?

/\[[^\]]*?(-)[^\[]*?\]/g

Match group extracted:

提取的匹配组:

"[a]-[a-gamma] - [[ - - [123-567567]]]"
       ^                    ^

Explanation available here: https://regex101.com/r/oC2xE0/1

可在此处获得解释:https://regex101.com/r/oC2xE0/1

#1


You can use

您可以使用

String n="[a]-[a-gamma]";
System.out.println(n.replaceAll("-(?=[^\\[\\]]*\\])", "_"));

As for the regex itself, I match the - symbol only if it is followed by non-[s and non-]s until the engine finds the ]. Then, we are "inside" the []s. There can be a situation when this is not quite true (4th hyphen in [a-z]-[a-z] - ] [a-z]), but I hope it is not your case.

至于正则表达式本身,我只匹配 - 符号,如果它后跟非[s和非] s,直到引擎找到]。然后,我们在[] s里面。可能存在这种情况并非如此([a-z] - [a-z] - ] [a-z]中的第4个连字符),但我希望不是你的情况。

IDEONE Demo

Output:

[a]-[a_gamma]

#2


-(?=[^\\[]*\\])

You can use this.See demo.

你可以使用它。参见演示。

https://regex101.com/r/bN8dL3/6

#3


Use a negative lookahead:

使用否定前瞻:

str = str.replaceAll("-(?![^\\]]*\\[)", "_");

The regex matches dashes whose next square bracket character is not an opening square bracket.

正则表达式匹配破折号,其下一个方括号字符不是左方括号。

#4


If your brackets are balanced (or if an unclosed bracket is considered opened by default until the end), you can use this way that needs few steps to find a match:

如果您的括号是平衡的(或者如果默认情况下将未关闭的括号打开直到结束),您可以使用这种方式来找到匹配项:

pattern:

((?:\\G(?!\\A)|[^\\[]*\\[)[^\\]-]*)-

replacement:

$1_

demo

pattern details:

(                   # open the capture group 1
    (?:             # open a non capturing group for the 2 possible beginings
        \\G (?!\\A) # this one succeeds immediately after the last match
      |
        [^\\[]* \\[ # this one reach the first opening bracket
                    # (so it is the first match)
    )
    [^\\]-]*        # all that is not a closing bracket or a dash
)                   # close the capture group
-                   # the dash

The \G anchor marks the position after the last match. But at the begining (since there isn't already a match), it matches by default the start of the string. This is the reason why I added (?!\A) to fail at the start of the string.

\ G锚标记最后一场比赛后的位置。但是在开始时(因为还没有匹配),它默认匹配字符串的开头。这就是我在字符串开头添加(?!\ A)失败的原因。

#5


How about this?

这个怎么样?

/\[[^\]]*?(-)[^\[]*?\]/g

Match group extracted:

提取的匹配组:

"[a]-[a-gamma] - [[ - - [123-567567]]]"
       ^                    ^

Explanation available here: https://regex101.com/r/oC2xE0/1

可在此处获得解释:https://regex101.com/r/oC2xE0/1