Android_programmer_camera
Android_programmer_camera

Reputation: 13369

Regular expression in Java that takes as input alphanumeric followed by forward slash and then again alphanumeric

I need a regular expression that takes as input alphanumeric followed by forward slash and then again alphanumeric. How do I write regular expression in Java for this?

Example for this is as follows:

adc9/fer4

I tried by using regular expression as follows:

String s = abc9/ferg5;
String pattern="^[a-zA-Z0-9_]+/[a-zA-z0-9_]*$";
if(s.matches(pattern))
{
    return true;
}

But the problem it is accepting all the strings of form abc9/ without checking after forward slash.

Upvotes: 1

Views: 898

Answers (5)

Steve Emmerson
Steve Emmerson

Reputation: 7832

I think the shortest Java regular expression that will do what I think you want is "^\\w+/\\w+$".

Upvotes: 0

Jay
Jay

Reputation: 27492

The asterisk should be a plus. In a regex, asterisk means 0 or more; plus means 1 or more. You used a plus after the part before the slash. You should also use a plus for the part after the slash.

Upvotes: 0

tchrist
tchrist

Reputation: 80443

This is the Java code needed to emulate what \w means:

public final static String
    identifier_chars = "\\pL"          /* all Letters      */
                     + "\\pM"          /* all Marks        */
                     + "\\p{Nd}"       /* Decimal Number   */
                     + "\\p{Nl}"       /* Letter Number    */
                     + "\\p{Pc}"       /* Connector Punctuation           */
                     + "["             /*    or else chars which are both */
                     +     "\\p{InEnclosedAlphanumerics}"
                     +   "&&"          /*    and also      */
                     +     "\\p{So}"   /* Other Symbol     */
                     + "]";

public final static String
identifier_charclass     = "["  + identifier_chars + "]";       /* \w */

public final static String
not_identifier_charclass = "[^" + identifier_chars + "]";       /* \W */

Now use identifier_charclass in a pattern wherever you want one \w character, and not_identifier_charclass wherever you want one \W character. It’s not quite up to the standard, but it is infinitely better than Java’s broken definitions for those.

Upvotes: 0

chkdsk
chkdsk

Reputation: 1195

Reference: http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html

Pattern p = Pattern.compile("[a-z\\d]+/[a-z\\d]+", CASE_INSENSITIVE);

Hope this helps.

Upvotes: 1

RedSoxFan
RedSoxFan

Reputation: 634

I would use:

String raw = "adc9/fer4";
String part1 = raw.replaceAll("([a-zA-Z0-9]+)/[a-zA-Z0-9]+","$1");
String part2 = raw.replaceAll("[a-zA-Z0-9]+/([a-zA-Z0-9]+)","$1");

[a-zA-Z0-9] allows any alphanumeric string + is one or more ([a-zA-Z0-9]+) means store the value of the group $1 means recall the first group

Upvotes: 0

Related Questions