如何使用正则表达式基于模式拆分字符串

时间:2021-05-17 21:43:12

I have trouble splitting string based on regex.

我无法根据正则表达式拆分字符串。

String str = "1=(1-2,3-4),2=2,3=3,4=4";
Pattern commaPattern = Pattern.compile("\\([0-9-]+,[0-9-]+\\)|(,)") ;
String[] arr = commaPattern.split(str);
for (String s : arr)
{
    System.out.println(s);
}

Expected output,

预期产量,

1=(1-2,3-4)     
2=2    
3=3    
4=4

Actual output,

实际产量,

1=

2=2
3=3
4=4

4 个解决方案

#1


5  

This regex would split as required

这个正则表达式将根据需要拆分

,(?![^()]*\\))
  ------------
      |->split with , only if it is not within ()

#2


3  

This isn't well suited for a split(...). Consider scanning through the input and matching instead:

这不适合拆分(...)。考虑扫描输入并匹配:

String str = "1=(1-2,3-4),2=2,3=3,4=4";

Matcher m = Pattern.compile("(\\d+)=(\\d+|\\([^)]*\\))").matcher(str);

while(m.find()) {
  String key = m.group(1);
  String value = m.group(2);
  System.out.printf("key=%s, value=%s\n", key, value);
}

which would print:

哪个会打印:

key=1, value=(1-2,3-4)
key=2, value=2
key=3, value=3
key=4, value=4

#3


1  

You will have to use some look ahead mechanism here. As I see it you are trying to split it on comma that is not in parenthesis. But your regular expressions says:

你将不得不在这里使用一些预见机制。正如我所看到的那样,您试图将其拆分为不在括号中的逗号。但是你的正则表达式说:

Split on comma OR on comma between numbers in parenthesis 

So your String gets splitted in 4 places 1) (1-2,3-4) 2-4) comma

所以你的String分为4个地方1)(1-2,3-4)2-4)逗号

#4


-4  

String[] arr = commaPattern.split(str);

should be

应该

String[] arr = str.split(commaPattern);

#1


5  

This regex would split as required

这个正则表达式将根据需要拆分

,(?![^()]*\\))
  ------------
      |->split with , only if it is not within ()

#2


3  

This isn't well suited for a split(...). Consider scanning through the input and matching instead:

这不适合拆分(...)。考虑扫描输入并匹配:

String str = "1=(1-2,3-4),2=2,3=3,4=4";

Matcher m = Pattern.compile("(\\d+)=(\\d+|\\([^)]*\\))").matcher(str);

while(m.find()) {
  String key = m.group(1);
  String value = m.group(2);
  System.out.printf("key=%s, value=%s\n", key, value);
}

which would print:

哪个会打印:

key=1, value=(1-2,3-4)
key=2, value=2
key=3, value=3
key=4, value=4

#3


1  

You will have to use some look ahead mechanism here. As I see it you are trying to split it on comma that is not in parenthesis. But your regular expressions says:

你将不得不在这里使用一些预见机制。正如我所看到的那样,您试图将其拆分为不在括号中的逗号。但是你的正则表达式说:

Split on comma OR on comma between numbers in parenthesis 

So your String gets splitted in 4 places 1) (1-2,3-4) 2-4) comma

所以你的String分为4个地方1)(1-2,3-4)2-4)逗号

#4


-4  

String[] arr = commaPattern.split(str);

should be

应该

String[] arr = str.split(commaPattern);

相关文章