英文:
String matching in math expression x <= 900 (int, int)
问题
以下是翻译好的部分:
我有一个数字,比如说900。
我提取一个带有格式的字符串 "x <= int (int, int)"
,例如: "x <= 900 (4, 7)"
。
我想要验证它是否符合格式 "x <= 900 (int, int)"
。
我如何使用字符串模式匹配器来实现呢?
我目前尝试了以下方法,但结果是false。
1) Pattern pattern = Pattern.compile("x <= 900 (\\d, \\d)");
2) Pattern pattern = Pattern.compile("x <= 900 ([0-9], [0-9])");
String expectedString = "x <= 900 (4, 7)";
Matcher m = pattern.matcher(expectedString);
System.out.println(m.matches());
英文:
I have the number, say 900.
I extract a string with the format "x <= int (int, int)"
for example. "x <= 900 (4, 7)"
I want to verify that it matches the format "x <= 900 (int, int)"
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("x <= 900 (\\d, \\d)");
2) Pattern pattern = Pattern.compile("x <= 900 ([0-9], [0-9])");
String expectedString = "x <= 900 (4, 7)";
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("x <= \\d+ \\(\\d+, \\d+\\)");
<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 <= [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 = "^x <= [0-9]+ \\([0-9]+, [0-9]+\\)$:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论