Pau*_*man 1 java regex android
我正在尝试使用正则表达式来匹配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
Run Code Online (Sandbox Code Playgroud)
编译器不喜欢\d(对于任何数字),它说唯一有效的转义是\b \t \n \f \r \" \' \\
只是为了yucks然后我尝试(\\d+) / (\\d+)并且它编译,但是不匹配.但是,nrGroups是2,如果没有匹配则没有意义.如何解析java中的数字组?在搜索论坛时,我发现只有C#帖子.
实际上,我最终希望能够匹配"12R/1234"使用(\d+).* / (\d+)"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
Run Code Online (Sandbox Code Playgroud)
另外,关于:
我最终希望能够使用(\ d +).*/(\ d +)来匹配"12R/1234"
不要.*用来匹配R- 清楚地识别出你匹配的东西.如果只有少量字符,则使用延迟量词(*?而不是*),或者如果不存在反斜杠,则使用否定组,例如(\d+)[^/]*/ (\d+)
另外,考虑分解一系列非数字,例如:
String myRunway = "12R / 1234";
String[] Groups = myRunway.split('\\D+');
String rwData = Groups[0];
String rwLen = Groups[1];
Run Code Online (Sandbox Code Playgroud)
这种方式不会与匹配器混淆 - 假设您的字符串是可预测/合适的格式.
| 归档时间: |
|
| 查看次数: |
4246 次 |
| 最近记录: |