简体   繁体   English

正则表达式用于拆分字符串以获取运算符

[英]Regex for splitting a string to get operators

I have a String = A+B+CC-D0. 我有一个字符串= A + B + CC-D0。 I want to use a regular expression to split it apart to get an array of of the ops {+,+,-} 我想使用正则表达式将其拆分以获取ops {+,+,-}的数组

I have tried the regular expression: 我试过正则表达式:

"[^+-]"

But the output gave me a array of { ,+,+, ,+}, why? 但是输出显示了一个{,+,+,,+}的数组,为什么?

    String s1 = "A+B+C-D";
    String s2 = "A0+B0";
    String[] op1 = s1.split([^+-]);
    String[] op2 = s2.split([^+-]);
    for(int i = 0; op1.length; i++){
        System.out.println(op1[i]);
    }

Here's the output: 这是输出:

Output of op1:
""
"+"
"+"
""
"-"

Output of op2:
""
""
"+"

Replace all the characters other than operators with empty string then split the resultant string according to the boundary which exists between two operators. 用空字符串替换除运算符以外的所有字符,然后根据两个运算符之间的边界分割结果字符串。

String s1 = "A+B+C-D";
String[] op1 = s1.replaceAll("[^+-]","").split("(?<=.)(?=.)");
for(String i: op1){
    System.out.println(i);
}

Output: 输出:

+
+
-
  • (?<=.) positive lookbehind which asserts that the match must be preceded by a character. (?<=.)正向后看,它断言匹配必须以字符开头。

  • (?=.) Positive lookahead which asserts that the match must be followed by a character. (?=.)正向超前,断言必须在匹配项后跟一个字符。

The problem is, you're splitting on single character, that is not + or - . 问题是,您正在分割单个字符,而不是+- When you split a string - ABC , it will get split 3 times - on A , B and C respectively, and hence you'll get an array - ["", "", "", ""] . 当您拆分字符串ABC ,它将分别在ABC上拆分3次-因此,您将获得一个数组- ["", "", "", ""]

To avoid this issue, use quantifier on regex: 为避免此问题,请在正则表达式上使用量词:

String s1 = "A+B+C-D";
String s2 = "A0+B0";
String[] op1 = s1.split("[^+-]+");
String[] op2 = s2.split("[^+-]+");
System.out.println(Arrays.toString(op1));
System.out.println(Arrays.toString(op2));

this is splitting on "[^+-]+" . 这在"[^+-]+"上分裂。

Now to remove the empty element at the beginning of array, you've to get rid of first delimiter from string, using replaceFirst() may be: 现在要删除数组开头的空元素,您必须使用replaceFirst()从字符串中删除第一个定界符,可能是:

String[] op1 = s1.replaceFirst("[^+-]+", "").split("[^+-]+");
System.out.println(Arrays.toString(op1)); // [+, +, -]

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

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