【发布时间】:2019-07-07 19:27:24
【问题描述】:
我想确定传递给函数的字符串是有效字符串。这样做时,字符串是一串多项式,它们之间必须有空格。
这些是有效的:
3x^7 3445x^233 3x 34 355
0
+3x^7 x^6 +3445x^233 -3x +34355 x^2
这些无效:
+3x^7+3445x^233-3x +34355
+3x^-7+3445x^233-3x +34355
一个空格不算。每个模式之间都必须有一个空格。如何在不从无效字符串中选择任何项目的情况下选择有效字符串?
我试过这个...
while (str.hasNext()) {
str.findInLine("([\\+-]*?\\b\\d+)x\\^([\\+-]*?\\d+\\b)"
+ "|([\\+-]*?\\b\\d+)x|([+-]*?\\d+)|\\^(\\d+)");
MatchResult m = str.match();
// When the term has a valid coefficient and power ie 3x^3
if (m.group(1) != null) {
coefficient = Integer.parseInt(m.group(1));
power = Integer.parseInt(m.group(2));
this.addTerm(coefficient, power);
}
// When the term ends in x ie 3x
else if (m.group(3) != null) {
coefficient = Integer.parseInt(m.group(3));
this.addTerm(coefficient, 1);
}
// When the term has no x ie -3
else if (m.group(4) != null) {
coefficient = Integer.parseInt(m.group(4));
this.addTerm(coefficient, 0);
}
// When the term has no coefficient ie x^3
else if (m.group(5) != null) {
power = Integer.parseInt(m.group(5));
this.addTerm(1, power);
}
}
如您所知,我的正则表达式接受所有有效组而不识别空格。
谢谢!
【问题讨论】:
-
"([+-]?((\\d+x?)|x)(\\^\\d+)?(\\s+|$))+"按预期验证提供的有效和无效字符串。您可以尝试将字符串按空格拆分并分别分析每个表达式以简化进一步的解析。
标签: java regex regex-negation regex-group regex-greedy