简体   繁体   中英

how to split this string by using regex?

I want to split this String:

5+(4/2)-4+1+(4%3)!=23+(3*5)

into a list , using regex .

The output should be:

[5 , + , ( , 4 , / , 2 , ) , - , 4 , + , 1 , + , ( , 4 , % , 3 , != , 23 , + , ( , 3 , * , 5 , ) ]

NOTE : My problem exactly is with the not equal operator , the regex does not consider it as a single character

Do matching instead of splitting.

List<String> list = new ArrayList<String>();
Matcher m = Pattern.compile("[^\\w()]?=|\\w+|\\W").matcher(s);
while(m.find()) {
   list.add(m.group())
 }
System.out.println(list);

DEMO

Please try this one

import java.util.ArrayList;
import java.util.List;


public class Test {
    public static void main(String[] args) {
    String s="5+(4/2)-4+1+(4%3)!=23+(3*5)";
    String s3 = "";
    char c = 0;
    List a1 = new ArrayList();
    for(int i=0;i<s.length();i++)
    {   
        char temp=c;
         c=s.charAt(i);
         String s1= Character.toString(c);
         String s2= Character.toString(temp);

         if((s1.equals("=") && s2.matches("!")))
         {
             s1=s2+s1;
             a1.add(s1);
         }
         else if(s1.matches("[0-9]+") ||(s1.equals("+") ||s1.equals("-") ||s1.equals("*") ||s1.equals("/")  ||s1.equals("%")||s1.equals("(")||s1.equals(")")) )
         {

                if(s1.matches("[0-9]+") )
                {   
                    s3=s3+s1;

                }
                else if(s1.equals("+") ||s1.equals("-") ||s1.equals("*") ||s1.equals("/")  ||s1.equals("%") ||s1.equals("(") ||s1.equals(")") )
                {
                    if(s3!="")
                    {
                    a1.add(s3);
                    }
                    a1.add(s1);
                    s3="";

                }

         }

    }

    System.out.println(a1);

    }
}

Hope it could help you!

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