在数学表达式中进行字符串匹配 x <= 900 (int, int)

huangapple go评论81阅读模式
英文:

String matching in math expression x <= 900 (int, int)

问题

以下是翻译好的部分:

我有一个数字,比如说900。
我提取一个带有格式的字符串 &quot;x &lt;= int (int, int)&quot;,例如: &quot;x &lt;= 900 (4, 7)&quot;
我想要验证它是否符合格式 &quot;x &lt;= 900 (int, int)&quot;

我如何使用字符串模式匹配器来实现呢?

我目前尝试了以下方法,但结果是false。

1)        Pattern pattern = Pattern.compile(&quot;x &lt;= 900 (\\d, \\d)&quot;);
2)        Pattern pattern = Pattern.compile(&quot;x &lt;= 900 ([0-9], [0-9])&quot;);

        String expectedString = &quot;x &lt;= 900 (4, 7)&quot;;

        Matcher m = pattern.matcher(expectedString);
        System.out.println(m.matches());
英文:

I have the number, say 900.
I extract a string with the format &quot;x &lt;= int (int, int)&quot; for example. &quot;x &lt;= 900 (4, 7)&quot;
I want to verify that it matches the format &quot;x &lt;= 900 (int, int)&quot;

How can I do it using String pattern matchers?

I have tried the following so far, the result is false.

1)        Pattern pattern = Pattern.compile(&quot;x &lt;= 900 (\\d, \\d)&quot;);
2)        Pattern pattern = Pattern.compile(&quot;x &lt;= 900 ([0-9], [0-9])&quot;);

        String expectedString = &quot;x &lt;= 900 (4, 7)&quot;;

        Matcher m = pattern.matcher(expectedString);
        System.out.println(m.matches());

答案1

得分: 0

你需要使用反斜杠(\)来转义括号,因为它们是正则表达式元字符。要匹配一个或多个数字,使用\d+

Pattern pattern = Pattern.compile("x <= \\d+ \\(\\d+, \\d+\\)");

<kbd>演示</kbd>

英文:

You need to escape the parentheses using backslashes (\) as they are regular expression metacharacters. To match one or more digits, use \d+.

Pattern pattern = Pattern.compile(&quot;x &lt;= \\d+ \\(\\d+, \\d+\\)&quot;);

<kbd>Demo</kbd>

答案2

得分: 0

尝试转义括号 - 否则,它会将括号内的所有内容解释为一个组(而不是像您想要的那样将括号视为文字字符)。以下是我做的一个示例(诚然,我使用的是 .NET 语法,但对于 Java,我认为类似):

^x <= [0-9]+ \\([0-9]+, [0-9]+\\)$

注意:在字符串中,您可能还需要转义 \\,所以字符串应该是:

String regex = "^x <= [0-9]+ \\([0-9]+, [0-9]+\\)$";
英文:

Try escaping the parenthesis - otherwise, it'll interpret everything inside the parenthesis as a group (instead of treating the parenthesis as a literal character like you want). Here's one I did (admittedly using .NET syntax, but it'll be similar for Java I think):

^x &lt;= [0-9]+ \([0-9]+, [0-9]+\)$

NOTE: in the string, you'll likely need to escape the \ too, so the string would be:

String regex = &quot;^x &lt;= [0-9]+ \\([0-9]+, [0-9]+\\)$:

huangapple
  • 本文由 发表于 2020年9月12日 00:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63850924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定