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

I have a URL with the separator "|##|"

I tried to separate this but didn't find solution.

3 Answers 3

4

Use Pattern.quote, it'll do the work for you:

Returns a literal pattern String for the specified String.

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

Now "|##|" is treated as the string literal "|##|" and not the regex "|##|". The problem is that you're not escaping the second pipe, it has a special meaning in regex.

An alternative solution (as suggested by @kocko), is escaping* the special characters manually:

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

* Escaping a special character is done by \, but in Java \ is represented as \\

Sign up to request clarification or add additional context in comments.

2 Comments

I like this approach (Pattern.quote)
That was super quick! +1
2

You have to escape the second |, as it is a regex operator:

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

Comments

1

You should try to understand the concept as well - String.split(String regex) interprets the parameter as a regular expression, and since pipe character "|" is a logical OR in regular expression, you would be getting result as an array of each alphabet is your word.
Even if you had used url.split("|"); you would have got same result.

Now why the String.contains(CharSequence s) passed the |##| in the start because it interprets the parameter as CharSequence and not a regular expression.

Bottom line: Check the API that how the particular method interprets the passed input. Like we have seen, in case of split() it interprets as regular expression while in case of contains() it interprets as character sequence.

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

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.