[PR]当たる!無料占いで仕事鑑定:大人気!無料占い『スピリチュアルの館』
Javaで正規表現を使う
戻る
詳しくは 本家サイトを参考に。
とりあえず基本的な使い方を以下に書いてみます。
◆セパレータを指定した文字列の分解
/*
* Uses split to break up a string of input separated by
* commas and/or whitespace.
*/
import java.util.regex.*;
public class Splitter {
public static void main(String[] args) throws Exception {
// Create a pattern to match breaks
Pattern p = Pattern.compile("[,\\s]+");
// Split input with the pattern
String[] result =
p.split("12, 3 4 , 5");
for (int i=0; i<result.length; i++)
System.out.println(result[i]);
}
}
Deja-Groove:/cygdrive/d/Work/java-test/regex> java -cp . Splitter
12
3
4
5
◆文字列置換
/*
* This code writes "我輩は犬である。犬も人並みにブログを書くのである。"
* to the standard-output stream:
*/
import java.util.regex.*;
public class Replacement {
public static void main(String[] args)
throws Exception {
// Create a pattern to match cat
Pattern p = Pattern.compile("猫");
// Create a matcher with an input string
Matcher m = p.matcher("我輩は猫である。猫も人並みにブログを書くのである。");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
// Loop through and create a new String
// with the replacements
while(result) {
m.appendReplacement(sb, "犬");
result = m.find();
}
// Add the last segment of input to
// the new String
m.appendTail(sb);
System.out.println(sb.toString());
}
}
Deja-Groove:/cygdrive/d/Work/java-test/regex> java -cp . Replacement
我輩は犬である。犬も人並みにブログを書くのである。
/*
* Checks for invalid characters
* in email addresses
*/
import java.util.regex.*;
import java.io.*;
public class EmailValidation {
public static void main(String[] args)
throws Exception {
String input = args[0];
//Checks for email addresses starting with
//inappropriate symbols like dots or @ signs.
Pattern p = Pattern.compile("^\\.|^\\@");
Matcher m = p.matcher(input);
if (m.find())
System.err.println("Email addresses don't start" +
" with dots or @ signs.");
//Checks for email addresses that start with
//www. and prints a message if it does.
p = Pattern.compile("^www\\.");
m = p.matcher(input);
if (m.find()) {
System.out.println("Email addresses don't start" +
" with \"www.\", only web pages do.");
}
p = Pattern.compile("[^A-Za-z0-9\\.\\@_\\-~#]+");
m = p.matcher(input);
StringBuffer sb = new StringBuffer();
boolean result = m.find();
boolean deletedIllegalChars = false;
while(result) {
deletedIllegalChars = true;
m.appendReplacement(sb, "");
result = m.find();
}
// Add the last segment of input to the new String
m.appendTail(sb);
input = sb.toString();
if (deletedIllegalChars) {
System.out.println("It contained incorrect characters" +
" , such as spaces or commas.");
}
}
}
Deja-Groove:/cygdrive/d/Work/java-test/regex> java -cp . EmailValidation .hhhhh@hhhh
Email addresses don't start with dots or @ signs.
戻る