Here are some points to stumble upon with Java regular expressions.
I feel that people who often use regular expressions in other languages are addicted to it.
Use the escape character \
when writing escape sequences.
However, if you want to express a "backslash" with a Java String type, you need to use one of the escape sequences, \\
.
I wasted a whole day.
Code that throws a compile error
void check() {
if (isFind("hoge.com")) {
//Can't run
}
}
boolean isFind(String text) {
//Compile error!!!!!
Pattern p = Pattern.compile("\.com");
return p.matcher(text).find();
}
Code that compiles
void check() {
if (isFind("hoge.com")) {
//Can be executed
}
}
boolean isFind(String text) {
Pattern p = Pattern.compile("\\.com");
return p.matcher(text).find();
}
The point is that if you want to represent the escape sequence \ .
in other languages, you need to write \\ .
.
The wording around here is confusing, so please refer to the comment section.
Matcher # group (int)
is not available immediatelyThe group (int)
method of the Matcher class throws a run-time error if you don't use the find ()
method.
That's because the find ()
method checks for a string match.
The group (int)
method is just the getter of the string matched by the find ()
method.
Code that throws a run-time error
Pattern p = Pattern.compile("(A*).");
void print() {
System.out.println(extract(AAABBB));
}
String extract(String text) {
Matcher m = p.matcher(text);
//Run-time error!!!!!
return m.group(1);
}
Code that can be executed properly
Pattern p = Pattern.compile("(A*).");
void print() {
System.out.println(extract(AAABBB)); //output: AAA
}
String extract(String text) {
Matcher m = p.matcher(text);
if (m.find()) {
return m.group(1);
} else {
return "";
}
}
Regular expressions are written in very different languages. If you think you're good at one language, it will hurt, so be careful.
~~ Perl is so easy! ~~
Recommended Posts