是否有根据运算符和负数分割表达式?
如果我有一个字符串"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 . . .
答案 0 :(得分:3)
这个正则表达式将:
正则表达式
(?:(?<=[-+/*^]|^)[-+])?\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验证器
在您的原始问题中,您只能对第二个值感兴趣。如果是这种情况,那么这就是你的正则表达式
(?:(?<=[-+/*^])[-+]?)\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