Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split String with this regular expression?

Tags:

java

regex

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.

like image 769
veerendra Avatar asked Jul 03 '26 02:07

veerendra


2 Answers

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 \\

like image 96
Maroun Avatar answered Jul 05 '26 18:07

Maroun


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

final String s[] = url.split("\\|##\\|");
like image 34
Konstantin Yovkov Avatar answered Jul 05 '26 17:07

Konstantin Yovkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!