java语言中的模式
我试图从字符串中获取信息,比如java语言中的模式,java,regex,Java,Regex,我试图从字符串中获取信息,比如(111222,ttt,qwerty) 价值清单 111 222 ttt qwerty 我尝试这种模式: String area = "(111,222,ttt,qwerty)"; String pattern = "\\([([^,]),*]+\\)"; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(area);
(111222,ttt,qwerty)
价值清单
- 111
- 222
- ttt
- qwerty
String area = "(111,222,ttt,qwerty)";
String pattern = "\\([([^,]),*]+\\)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(area);
System.out.println(m.groupCount());
ArrayList<String> values = new ArrayList<String>();
while(m.find()){
System.out.println("group="+m.group(1));
values.add(m.group());
}
stringarea=“(111222,ttt,qwerty)”;
字符串模式=“\\([([^,]),*]+\\)”;
Pattern p=Pattern.compile(Pattern);
匹配器m=p.匹配器(面积);
System.out.println(m.groupCount());
ArrayList值=新的ArrayList();
while(m.find()){
System.out.println(“group=“+m.group(1));
添加(m.group());
}
但我发现组数是零。我错过了什么?应该是
(…)+
而不是[…]+
(字符)。假设您总是使用相同格式的字符串,您可以尝试:
String[] split = area.split("\\(|\\)|,");
如果只有包含英文字母和数字且没有空格的单词 您可以使用以下regexp来实现这一点
String pattern = "[a-zA-Z0-9]+";
它检查只包含数字和大写/小写英文字母的字符组。如果您知道只有一组括号()
注意,除了结果字符串[]中需要的字符串外,它还将返回一些空字符串
String text = "aaa,bbb(111,222,ttt,qwerty),,,cc,,dd";
String[] parts = text.substring(text.indexOf('(')+1, text.indexOf(')')).split(",");
// parts = [ 111, 222, ttt, qwerty ]