繁体   English   中英

正则表达式在运算符之后拆分数学表达式并查找负数

[英]Regex splitting mathematical expression after operators and look for a negative number

有没有根据运算符和负数分割表达式?

如果我有一个字符串"2+-2" ,我希望-2成为我的数组中的对象?

    String exp = "2+-2";
    String[] temp = new String[exp.length()];
    temp =exp.split("(?<=[-+*/^])|(?=[-+*/^])");
    Stack<String> stack = new Stack<String>();
    LinkedList <String>list= new LinkedList<String>();
    for (int i=0; i<temp.length; i++) {
        String s = temp[i]+"";
        if(s.equals("-")) {
           while(!stack.isEmpty())
           {
              String tkn=stack.pop();
              if(tkn.equals("*")|| tkn.equals("/") || tkn.equals("+")||tkn.equals("-")||tkn.equals("^"))
                  list.add(tkn);
              else{
                  stack.push(tkn);
                  break;
              }
           }
           stack.push(s);
. . . for every operator . . .

描述

这个正则表达式将:

  • 找到数学方程式中的所有数字
  • 捕获所有数字并将它们作为数组返回
  • 如果包含在数字中,则捕获正号或负号

正则表达式

(?:(?<=[-+/*^]|^)[-+])?\d+(?:[.]\d+)?

正则表达式可视化

示例Java代码

import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
  public static void main(String[] asd){
  String sourcestring = "source string to match with pattern";
  Pattern re = Pattern.compile("(?:(?<=[-+/*^])[-+]?)\\d+(?:[.]\\d+)?",Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
  Matcher m = re.matcher(sourcestring);
  int mIdx = 0;
    while (m.find()){
      for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
        System.out.println( "[" + mIdx + "][" + groupIdx + "] = " + m.group(groupIdx));
      }
      mIdx++;
    }
  }
}

示范文本

1+1
2.1+-2.2
3.1+3.2
4.1--4.2
5.1-+5.2
-6.1--6.2
7.1-7.2

捕获组

[0] => 1
[1] => 1
[2] => 2.1
[3] => -2.2
[4] => 3.1
[5] => 3.2
[6] => 4.1
[7] => -4.2
[8] => 5.1
[9] => +5.2
[10] => 6.1
[11] => -6.2
[12] => 7.1
[13] => 7.2

在线Java验证器

http://fiddle.re/b2w5wa

额外

在您的原始问题中,您只能对第二个值感兴趣。 如果是这种情况那么这就是你的正则表达式

(?:(?<=[-+/*^])[-+]?)\d+(?:[.]\d+)?

捕获组

[0] => 1
[1] => -2.2
[2] => 3.2
[3] => -4.2
[4] => +5.2
[5] => 6.1
[6] => -6.2
[7] => 7.2

暂无
暂无

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

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