java Java拆分正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2660342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java split regular expression
提问by Danny King
If I have a string, e.g.
如果我有一个字符串,例如
setting=value
How can I remove the '=' and turn that into two separate strings containing 'setting' and 'value' respectively?
如何删除“=”并将其转换为两个单独的字符串,分别包含“设置”和“值”?
Thanks very much!
非常感谢!
回答by cletus
Two options spring to mind.
两个选项浮现在脑海中。
The first split()s the Stringon =:
第一个split()S中String上=:
String[] pieces = s.split("=", 2);
String name = pieces[0];
String value = pieces.length > 1 ? pieces[1] : null;
The second uses regexes directly to parse the String:
第二个直接使用正则表达式来解析String:
Pattern p = Pattern.compile("(.*?)=(.*)");
Matcher m = p.matcher(s);
if (m.matches()) {
String name = m.group(1);
String value = m.group(2);
}
The second gives you more power. For example you can automatically lose white space if you change the pattern to:
第二个给你更多的力量。例如,如果将模式更改为:
Pattern p = Pattern.compile("\s*(.*?)\s*=\s*(.*)\s*");

