JAVAは正規表現を使う
主にmatches()/lookingAt()/find()の3つの方法の違いを明らかにし,replaceAll()replaceFirst()appendReplacement()を使用する. appendTail()コードを見てください
出力結果は次のとおりです.
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegTest {
public static void main(String[] args)
{
Pattern reg = Pattern.compile("(20\\d{2})-([01]\\d)-([0-3]\\d)");
Matcher matcher = null;
System.out.println(reg.pattern());
matcher = reg.matcher("2012-02-25");
//matches() ,
if (matcher.matches())
{
System.out.println("time:"+matcher.group(0));
System.out.println("year:"+matcher.group(1));
System.out.println("year:"+matcher.group(2));
System.out.println("year:"+matcher.group(3));
}
Pattern reg2 = Pattern.compile("\\d*");
System.out.println(reg2.pattern());
matcher = reg2.matcher("2012abcd");
//lookingAt()
if (matcher.lookingAt())
{
System.out.println("num:"+matcher.group());
}
Pattern reg3 = Pattern.compile("\\d+");
System.out.println(reg3.pattern());
matcher = reg3.matcher("asf2012abcd2011jdf2010jk");
//find()
while(matcher.find())
{
System.out.println("matcherStr:"+matcher.group());
}
//appendReplacement() , StringBuffer
Pattern reg4 = Pattern.compile("(hello|goodbye)");
matcher = reg4.matcher("sayhelloandsaygoodbyeandsayhelloandsaysomething");
StringBuffer sb = new StringBuffer();
while (matcher.find()){
System.out.println("matcherStr:"+matcher.group());
matcher.appendReplacement(sb, "IT");
System.out.println("sb:"+sb);
}
//appendTail() StringBuffer
// appendReplacement
matcher.appendTail(sb);
System.out.println("sb:"+sb);
}
}
出力結果は次のとおりです.
(20\d{2})-([01]\d)-([0-3]\d)
time:2012-02-25
year:2012
year:02
year:25
\d*
num:2012
\d+
matcherStr:2012
matcherStr:2011
matcherStr:2010
matcherStr:hello
sb:sayIT
matcherStr:goodbye
sb:sayITandsayIT
matcherStr:hello
sb:sayITandsayITandsayIT
sb:sayITandsayITandsayITandsaysomething