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 acc开发者_C百科epting all the strings of form abc9/ without checking after forward slash.
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.
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
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.
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.
I think the shortest Java regular expression that will do what I think you want is "^\\w+/\\w+$"
.
精彩评论