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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:15:37  来源:igfitidea点击:

Java split regular expression

javaregex

提问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*");

回答by Michael Mrozek

You don't need a regular expression for this, just do:

您不需要为此使用正则表达式,只需执行以下操作:

String str = "setting=value";
String[] split = str.split("=");
// str[0] == "setting", str[1] == "value"

You might want to set a limitif valuecan have an =in it too; see the javadoc

你可能想设置一个limitifvalue也可以有一个=;见javadoc