开发者

Java split regular expression

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' respective开发者_如何学运维ly?

Thanks very much!


Two options spring to mind.

The first split()s the String on =:

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:

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


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 limit if value can have an = in it too; see the javadoc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜