This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Use regex for this? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Use regex for this?" Watch "Use regex for this?" New topic
Author

Use regex for this?

Denise Hum
Greenhorn

Joined: Oct 09, 2001
Posts: 20
Okay, I'm just returning to Java & programming after a few years hiatus.

I'm trying to see if a string consists of only alphanumeric characters. Is using regular expressions for this appropriate? That is, a String like "555-aws" is bad while "3lsfs" is good.

Here's the code I'm using which doesn't seem to work for more than one character. (I know, the pattern doesn't look for digits yet.) What regular expression should I be using?

String s = "ss";
Pattern p = Pattern.compile("[a-z]");
Matcher m = p.matcher(s);
System.out.println(m.matches());

Thanks.
Max Habibi
town drunk
( and author)
Sheriff

Joined: Jun 27, 2002
Posts: 4118
Hi Denise,

You probably want to add a * to the end of your expression, indicating that it can repeat one or more times. Also, you want to consider upper case characters, and digits. If you're allowed to have underscores, you may want to use the following meta character.
\w \\A word character: [a-zA-Z_0-9]

HTH,
M
[ September 13, 2005: Message edited by: Max Habibi ]

Java Regular Expressions
Denise Hum
Greenhorn

Joined: Oct 09, 2001
Posts: 20
Thanks. I forgot about the *.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Use regex for this?
 
Similar Threads
String --> split/regex question
Splitting a String into an array using split()
Adding Image, Bolds to JTextPane
java parsing using regular expression
string extraction using regular expressions