How do I split a String with this regex?

if (url.contains("|##|")) {
    Log.e("url data", "" + url);
    final String s[] = url.split("\\|##|");
}

      

I have a delimited url "|##|"

I tried to separate this but couldn't find a solution.

+3


source to share


3 answers


Use it Pattern.quote

, it will work for you:

Returns the String pattern for the specified string.

final String s[] = url.split(Pattern.quote("|##|"));

      

Now "| ## |" treated as a string literal "| ## |" not the regular expression "| ## |" ... The problem is that you are not avoiding the second pipe, this has a special meaning in regex.



An alternative solution (as suggested by @kocko), speed up * special characters manually:

final String s[] = url.split("\\|##\\|");

      

* Special character escaping is done \

, but in Java it \

is represented as\\

+4


source


You need to avoid the second |

one as this is the regex operator:



final String s[] = url.split("\\|##\\|");

      

+2


source


You should also try to understand the concept - String.split(String regex)

interprets the parameter as a regular expression, and since the pipe character "|" is logical OR in regex, you get the result as the array of each alphabet is your word.
Even if you used url.split("|");

, you would have the same result.

Now why is it String.contains(CharSequence s)

passed |##|

at the beginning, because it interprets the parameter as a CharSequence, not a regex.

Bottom line: Check the API like how a particular method interprets the passed input. As we saw, in the case of split (), it is interpreted as a regular expression, and in the case of contains (), it is interpreted as a sequence of characters.

You can check out regex constructs here - http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

+1


source







All Articles