gpt4 book ai didi

java - 正则表达式匹配android java中的数字

转载 作者:行者123 更新时间:2023-11-29 06:44:28 25 4
gpt4 key购买 nike

我正在尝试使用正则表达式来匹配 java 中的数字,例如:

Pattern p = Pattern.compile("(\d+) / (\d+)");
String myRunway = "12 / 1234";
Matcher m = p.matcher(myRunway);
int nrGroups = m.groupCount();
String rwData = m.group(1); //should have 12
String rwLen = m.group(2); //should have 1234

编译器不喜欢 \d(对于任何数字),它说唯一有效的转义符是 \b\t\n\f\r\"\'\\

真讨厌,然后我尝试了 (\\d+)/(\\d+) 并且它编译了,但不匹配。但是,nrGroups 是 2,如果没有匹配,则没有意义。我如何解析 java 中的数字组?在搜索论坛时,我发现只有 C# 帖子。

实际上,我最终希望能够使用 (\d+).*/(\d+) 来匹配“12R/1234”,以获得“12”和“1234”作为两组,但我简化了上面的内容以尝试使其正常工作。

谢谢!

最佳答案

Java 字符串需要其中的任何反斜杠进行转义。

所以你需要使用 \\d 来让 \d 通过正则表达式模式。

同样,如果您想要双引号,则需要使用 \" - 要清楚这是在 Java 字符串方面,而不是正则表达式方面。


您的 (\\d+)/(\\d+) 版本应该匹配...我认为问题是您没有执行 m.find()所以它没有填充组。即试试这个:

Pattern p = Pattern.compile("(\\d+) / (\\d+)");
String myRunway = "12 / 1234";
Matcher m = p.matcher(myRunway);
m.find(); // <----- this 'executes' the matcher, and populates the group info
int nrGroups = m.groupCount();
String rwData = m.group(1); //should have 12
String rwLen = m.group(2); //should have 1234


另外,关于:

I eventually want to be able to match "12R / 1234" using (\d+).* / (\d+) to

不要使用 .* 来匹配 R - 清楚地标识您要匹配的内容。如果只有少量字符,请改用惰性量词(即 *? 而不是 *),或者如果不能有反斜杠,则使用否定组,例如(\d+)[^/]*/(\d+)

此外,考虑拆分一系列非数字,例如:

String myRunway = "12R / 1234";
String[] Groups = myRunway.split('\\D+');
String rwData = Groups[0];
String rwLen = Groups[1];

不要以这种方式乱用匹配器 - 假设您的字符串采用可预测/合适的格式。

关于java - 正则表达式匹配android java中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7314252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com