简体   繁体   中英

split a string without adjacent characters that matched regex in java

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.

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.]

I suppose it's impossible to split your string by regex as you wish. The problem is that [^\\&]\\&[^\\&] matches 3 characters -> d&S and it splits by 3 characters, so you have them removed. You can use Pattern and Matcher to split a string in this way:

    String s = "conditional&&operator and ampersand&Symbol.";
    final Matcher matcher = Pattern.compile("[^&]&[^&]").matcher(s);
    if (matcher.find()) {
        final int indexOfMatchStart = matcher.start();
        final String firstPart = s.substring(0, indexOfMatchStart + 1); // + 1 to include first symbol of RegEx
        final String secondPart = s.substring(indexOfMatchStart + 2); // + 2  to skip &
        System.out.println(firstPart + secondPart); // will print conditional&&operator and ampersandSymbol.
    }

Try this,

Long code but Basic logic.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class B {

    public static void main(final String[] args) {

        final String x = "conditional&&operator and ampersand&Symbol.";

        final String mydata = x;
        String delimString = "";
        final Pattern pattern = Pattern.compile("[^\\&]\\&[^\\&]");
        final Matcher m = pattern.matcher(mydata);
        while (m.find()){
            delimString = m.group(0);
        }


    final String[] result = x.split(delimString); // Split using 'd&S'
    final String[] conResult = delimString.split("&"); //Split d&S in d and s
    System.out.println(result[0]+""+conResult[0]); // append d at the end of string
    System.out.println(conResult[1]+""+result[1]); // append s at the start of string

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM