SiNBLOG

140文字に入らないことを、極稀に書くBlog

Java正規表現サンプルメモ



import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class MatchSample {
public static void main(String[] args) {
String txt = "pokemon, pikachu, fire45, thunder";
String regex = "([a-z0-9]+), ([a-z0-9]+), ([a-z0-9]+), ([a-z0-9]+)";
Pattern p = Pattern.compile(regex);

Matcher m = p.matcher(txt);

while(m.find()){
System.out.println("GROUP COUNT = " + m.groupCount());
for(int j = 1; j <= m.groupCount(); j++) {
System.out.println("j = "+ j + "--" + m.group(j));
}
}

System.out.println("------------------------------");
String regex1 = "([a-z0-9]+)+";
p = Pattern.compile(regex1);

m = p.matcher(txt);

while(m.find()){
System.out.println("GROUP COUNT = " + m.groupCount());
for(int j = 1; j <= m.groupCount(); j++) {
System.out.println("j = "+ j + "--" + m.group(j));
}
}

}
}

//結果
GROUP COUNT = 4
j = 1--pokemon
j = 2--pikachu
j = 3--fire45
j = 4--thunder

                                                          • -

GROUP COUNT = 1
j = 1--pokemon
GROUP COUNT = 1
j = 1--pikachu
GROUP COUNT = 1
j = 1--fire45
GROUP COUNT = 1
j = 1--thunder