Showing posts with label regex Alphanumeric and Punctuation Java. Show all posts
Showing posts with label regex Alphanumeric and Punctuation Java. Show all posts

Monday, February 28, 2011

Java regex to match words with only Alphanumeric and Punctuation characters

The title says it:

 private static final String onlyAlphaNumericAndPunctuationRegex = "[\\p{Alnum}\\p{Punct}]*";

//returns true
"0123!\"#$%&<=~abcijkxyzABC".matches(onlyAlphaNumericAndPunctuationRegex);

//returns false
"hello test space".matches(onlyAlphaNumericAndPunctuationRegex);

//returns false
"some_àèìòù-ÀÈÌÒÙ_more".matches(onlyAlphaNumericAndPunctuationRegex);


if you need to have at least one character change the regex to:

"[\\p{Alnum}\\p{Punct}]{1,}";