1

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!

2 Answers 2

10

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*");
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

That is using regular expression, though. For example, if you want to split on ?, you can't just str.split("?"). You'd have to escape it to str.split("\\?").
Ah yes, I forgot Java's String.split takes a regular expression; most languages split on a string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.