簡體   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