1

Suppose I want to split a string by either space character or the %20 string, how should I write my regex?

I tried the following, but it didn't work.

String regex = "[\\s+, %20]";
String str1 =  "abc%20xyz";
String str2 = "abc xyz";

str1.split(regex);
str2.split(regex);

The regex doesn't seem to work on str1.

3 Answers 3

3

use the alternation |:

String regex = "(?:\\s+|%20)+";
Sign up to request clarification or add additional context in comments.

4 Comments

Whats' the meaning of ?:?
@OneTwoThree: (?:...) is for grouping without capturing
Wait, but this is not the same as what I'd want. (I believe this regex means to split by one or more '%20', which is not what I want.)
@OneTwoThree: I am not sure what you are looking for, but you have now all the tools to make your own pattern.
1
String regex = "(\\s{1}+|%20{1}+)";

3 Comments

In your {1}+ is like saying I want exactly one of those characters once or more times?
No,{1}+is like say once times,++means once or more times,e.g. "abc%20%20%20xyz".split("([%20]++)").length==2; but "abc%20%20%20xyz".split("(%20+)").length==4;
Hmm that is interesting. Thanks for piquing my curiosity, I'll have to read up on this.
0

If you want to split by ONE space or ONE "%20", try this:

String regex = "(\\s|%20)";

If you want to split by AT LEAST ONE space or AT LEAST ONE "%20", then try this:

String regex = "(\\s+|(%20)+)";

Comments

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.