I am new to Android coding, but I have experience with Perl regex.
I need to match a list of 0 or more identifiers with a regular expression like:
^\s*((\w\d\d\d)(\s+$2)*)?$
Note the $2 refers to the previous matched group (\w\d\d\d)
For android code it would look like:
Pattern.compile("^\\s*((\\w\\d\\d\\d)(\\s+\$2)*)?$")
Eclipse compiler does not compile the \$2, I tried also \2, which compiles but tries to match a literal number 2.
The brute force solution would be to repeat the identifier pattern:
Pattern.compile("^\\s*((\\w\\d\\d\\d)(\\s+(\\w\\d\\d\\d))*)?$")
It works, but it has the following disadvantages:
* It is easy to make a syntax error in either repetition
* as the identifier gets more complicated the string gets big
* it is not elegant
* gets much more complicated if you need to refer not to one but several previous matches
Is there a way in Java to refer to previous matched groups within the regex?
I am sorry about the confusion, my confusion.
The regex:
will match something like “A12 A12”, therefore matching the previous match. (I just tried it on Eclipse and followed it with the debugger)
What I wanted is a way to write a short regex for a string like “A12 B35 C36 A011”
In perl you can use variables a part of the pattern, therefore it can be done in perl:
Short and simple. Therefore I assumed in java it can also be done by concatenating strings (I just tried it and it works)
It is not elegant, but it does the job.