简体   繁体   English

如何使用正则表达式拆分此字符串?

[英]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 . 使用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 注意:我的问题完全是not equal运算符, regex不将其视为单个字符

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 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! 希望它能对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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