我在一个项目中可以接受用户的字符串,用户可以在一行中全部输入负正值。
然后,我使用正则表达式将其拆分为一个空格。我现在需要能够“修复”数组以包含数字和运算符。
"(?<=[\\(\\)\\+\\-*\\/\\^A-Za-z])|(?=[\\(\\)\\+\\-*\\/\\^A-Za-z])"
例如,用户可以输入 -1 / 2-1/2
我现在需要元素像 arr [1] = -1 arr [2] = 2(或/也可以)
当前它可以做到:
-
1
/
2
-
1
/
2
我开始写案例,就像arr [i] .equals(“-”)然后也抓住下一个数字一样。嗯,这行不通,因为他们中间可以有-。
任何想法都值得赞赏。
答案 0 :(得分:0)
我猜也许有些表达类似于
-?\s*[0-9.]+|([+÷*-])
如果可以在以后进行验证,则可能可以开始。
尽管您可能要在此处完成一些设计问题。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class re{
public static void main(String[] args){
final String regex = "-?\\s*[0-9.]+|([+÷*-])";
final String string = "-1 /2 - 1/2.4\n"
+ "-1 /25 -- 1/23.2\n"
+ "-1 / 29 - 1/212.42\n"
+ "-1 / 2 - -1/2\n"
+ "-1 / 2 * -1/2\n"
+ "-1 / 2 + -1/2\n"
+ "-1 / 2 ÷ -1/2";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: - 1
Group 1: null
Full match: 2.4
Group 1: null
Full match: -1
Group 1: null
Full match: 25
Group 1: null
Full match: -
Group 1: -
Full match: - 1
Group 1: null
Full match: 23.2
Group 1: null
Full match: -1
Group 1: null
Full match: 29
Group 1: null
Full match: - 1
Group 1: null
Full match: 212.42
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -
Group 1: -
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: *
Group 1: *
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: +
Group 1: +
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: ÷
Group 1: ÷
Full match: -1
Group 1: null
Full match: 2
Group 1: null
如果您想探索/简化/修改表达式,可以 在右上角的面板上进行了说明 regex101.com。如果您愿意, 也可以在this link中观看它的匹配方式 针对一些样本输入。