[Shootout-list] Java Regular-expression pattern-matching code
Paul Lofte
plofte@raleys.com
Fri, 4 Mar 2005 16:12:00 -0800
Thought it would be nice to simplify the code a bit.
Since we're using sun 1.4.2_05 I figured why not use the regex utilities
provided. =20
For this example I didn't see the need to use a different api.
=20
>From past messages on the board, it looks like people just post the code
along with the message.
I'm not really sure about the etiquette, just wanted to contribute.
-Paul=20
=20
Here's the code:
=20
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
=20
public class regexmatch {
=20
public static void main(String args[]) {
=20
try {
String regex =3D "(^|^\\D*[^\\(\\d])" // must be =
preceeded
by non-digit
+ "((\\(\\d\\d\\d\\))|(\\d\\d\\d))" // match 2: Area
Code inner match 3: area with perens,=20
//
inner match 4: without perens=20
+ "[ ]" // area code
followed by one space
+ "(\\d\\d\\d)" //match 5: prefix of
3 digits
+ "[ -]" // prefix followed
by space or dash
+ "(\\d\\d\\d\\d)" // match 6: last 4
digits
+ "(\\D*$)"; // followed by non
numeric chars=20
=20
Pattern phonePattern =3D Pattern.compile(regex);
BufferedReader in =3D new BufferedReader(new
InputStreamReader(System.in));
String line;
int count =3D 0;
while ((line =3D in.readLine()) !=3D null) {
Matcher match =3D phonePattern.matcher(line);
if (match.matches()) {
count++;
if (match.group(3) !=3D null) {
System.out.println(count + ": "=20
+ match.group(3) + " "=20
+ match.group(5) + "-"=20
+ match.group(6));
} else {
System.out.println(count + ": ("=20
+ match.group(4) + ") "=20
+ match.group(5) + "-"=20
+ match.group(6));
}
}
=20
}
in.close();
} catch (IOException e) {
System.err.println(e);
}
System.exit(0);
}
}