[英]Regular expressions (denominator of a fraction)
Soo i think i already solved it, what i did: 太好了,我想我已经解决了,我做了什么:
String pattern = "(<=|>=)\\s{0,2}((+]\\s{0,2})?(\\d+\\s{0,2}[/]\\s{0,2}(\\d{2,}|[1-9])\\s{0,2}|\\d+[.]\\d{1,2}|\\d+))\\s{0,2}";
The pattern had something wrong, i have corrected it above and now it works :) 该模式有问题,我已经在上面进行了更正,现在可以正常工作了:)
I have an inequation that may containing >= or <=, some white spaces and a number. 我有一个不等式,可能包含> =或<=,一些空格和一个数字。 That number might be an integer, a decimal number with 2 decimal places or a fraction and I want to retrieve the number on the 2nd member of the inequation with the "Matcher". 该数字可能是整数,带2个小数位的十进制数字或一个小数,我想用“ Matcher”检索不等式的第二个成员上的数字。 Example: 例:
4x1 + 6x2 <= 40/3
I've tried to construct such a pattern and I was able to find it. 我已经尝试构建这样的模式,但是我能够找到它。 But then I've remembered that a fraction cannot be divided by zero so I want to check that aswell. 但是后来我想起了一个分数不能被零除的原因,所以我也想检查一下。 For that I have used the following code: 为此,我使用了以下代码:
String inequation = "4x1 + 6x2 <= 40/3";
String pattern = "(<=|>=)\\s{0,2}((+]\\s{0,2})?(\\d+\\s{0,2}[/]\\s{0,2}(\\d{2,}|[1-9])\\s{0,2}\\d+|\\d+[.]\\d{1,2}|\\d+))\\s{0,2}";
Pattern ptrn = Pattern.compile(pattern);
Matcher match = ptrn.matcher(inequation);
if(match.find()){
String fraction = match.group(2);
System.out.println(fraction);
} else {
System.out.println("NO MATCH");
}
But it's not working as expected. 但是它没有按预期工作。 If it has at least 2 digits on the denominator it returns correctly (eg 40/32). 如果分母上至少有两位数字,它将正确返回(例如40/32)。 But if it only has 1 digit it only returns the integer part (eg 40). 但是,如果只有1位数字,则仅返回整数部分(例如40)。
Anyway to solve this? 无论如何要解决这个问题? Which expression should I use? 我应该使用哪种表达方式?
You could try using debuggex to build regular expressions. 您可以尝试使用debuggex构建正则表达式。 It shows you a nice diagram of your expression and you can test your inputs as well. 它显示了一个漂亮的表达式图表,您也可以测试输入。
Java implementation (validates that the numerator is non-zero.): Java实现 (验证分子非零。):
Matcher m = Pattern.compile("[<>]=?\\s{0,2}([0-9]*(/[1-9][0-9]*)?)$").matcher("4x1 + 6x2 <= 40/3");
if (m.find()) {
System.out.println(m.group(1));
}
You need an '$' at the end of your expression, so that it tries to match the entire inequality. 表达式的末尾需要一个“ $”,以便它尝试匹配整个不等式。
Do you just want the number after the inequality sign? 您是否只需要不等号后的数字? Then do: 然后做:
Matcher m = Pattern.compile("[<>]=?\\s*(.+?)\\s*$").matcher(string);
String number = m.find() ? m.group(1) : null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.