Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string without adjacent characters that matched regex in java

Tags:

java

regex

split

i am first to this site. I want to split a string without the characters that matched in regex of string split method in java.

The string for splitting is (for eg.) : "conditional&&operator and ampersand&Symbol."
My regex-expression for spit is : "[^\\&]\\&[^\\&]"
My expectation is : [conditional&&operator and ampersand, Symbol]
But, the output is : [conditional&&operator and *ampersan, ymbol*]

The code i used is:

String s = "conditional&&operator and ampersand&Symbol.";     
String[] sarr = s.split("[^\\&]\\&[^\\&]");     
System.out.println(Arrays.toString(sarr));     

So, please tell me what regex i should use to get the expected output, that is without the additional characters removed.

like image 412
Logesh-0304 Avatar asked Jul 05 '26 19:07

Logesh-0304


1 Answers

Your question is very similar to this one.

What you need is a negative look-behind. In your case, you could use something like:

String s = "conditional&&operator and ampersand&Symbol.";
String[] sarr = s.split("(?<!&)&(?!&)");
System.out.println(Arrays.toString(sarr));
// output: [conditional&&operator and ampersand, Symbol.]
like image 158
rph Avatar answered Jul 07 '26 09:07

rph



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!