I’m trying to use regex to match digits in java, something like:
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
The compiler doesn’t like \d (for any digit), it says the only valid escapes are \b \t \n \f \r \" \' \\
Just for yucks I then tried (\\d+) / (\\d+) and it compiles, but does not match. However, nrGroups is 2 which doesn’t make sense if there was no match. How do I parse groups of digits in java? In searching the forum, I found only C# postings on this.
Actually, I eventually want to be able to match “12R / 1234” using (\d+).* / (\d+) to get “12” and “1234” as the two groups, but I simplified the above to try to get it working.
Thanks!
Java strings need any backslashes in them to be escaped.
So you need to use
\\din order to get\dpassed through for the regex pattern.Similarly you’d need to use
\"if you wanted a double-quote – to be clear this is on the Java string side, not the regex side of things.Your
(\\d+) / (\\d+)version should have matched… I think the problem was that you didn’t do anm.find()so it didn’t populate the groups. i.e. try this:Also, regarding:
Don’t use
.*to matchR– identify clearly what you are matching. If there is only a small number of characters, use a lazy quantifier instead (that’s*?instead of*), or if there can’t be a backslash then use a negated group, e.g.(\d+)[^/]*/ (\d+)Also, consider perhaps splitting on a series of non-digits instead, something like:
No messing about with matchers that way – assuming your string is in a predictable/suitable format.