[英]Regex splitting mathematical expression after operators and look for a negative number
Is there someway to split an expression according to operators and negative numbers? 有没有根据运算符和负数分割表达式?
if I have a string "2+-2"
, I want the -2
to be the object in my array? 如果我有一个字符串"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 . . .
This regex will: 这个正则表达式将:
Regex 正则表达式
(?:(?<=[-+/*^]|^)[-+])?\d+(?:[.]\d+)?
Sample Java Code 示例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++;
}
}
}
Sample Text 示范文本
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
Capture Groups 捕获组
[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
Online Java Validator 在线Java验证器
http://fiddle.re/b2w5wa http://fiddle.re/b2w5wa
In your original question you eluded to only being interested in the second value. 在您的原始问题中,您只能对第二个值感兴趣。 If that is the case then this is the regex for you 如果是这种情况那么这就是你的正则表达式
(?:(?<=[-+/*^])[-+]?)\d+(?:[.]\d+)?
Capture Groups 捕获组
[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.