Skip to content

Instantly share code, notes, and snippets.

@seyan
Created March 24, 2011 05:03
Show Gist options
  • Save seyan/884605 to your computer and use it in GitHub Desktop.
Save seyan/884605 to your computer and use it in GitHub Desktop.
正規表現による入力値検証
// 1文字以上30文字以下の「制御文字以外の」文字列を判別する正規表現
private static final String REGEX_ADDRESS2 = "\\P{Cc}{1,30}";
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexpSample {
/** 英数字の1文字以上5文字以下 */
private static final String REGEX = "[0-9a-z]{1,5}";
/**
* 正規表現を満たすかどうかの判定メソッド
* @param str 判定対象となる文字列
* @param regex 正規表現パターン
* @return
*/
private static boolean isMatchRegexp(String str, String regex){
//大文字・小文字を区別しない
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
return m.matches();
}
/**
* 動作確認
*/
public static void main(String[] args) {
String s1 = "abcD";
String s2 = "125Za";
String s3 = "aaaaaa";
String s4 = "#abc";
System.out.println("s1 : " + isMatchRegexp(s1, REGEX));
System.out.println("s2 : " + isMatchRegexp(s2, REGEX));
System.out.println("s3 : " + isMatchRegexp(s3, REGEX));
System.out.println("s4 : " + isMatchRegexp(s4, REGEX));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment