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

痞子三分冷 提交于 2019-12-13 02:06:10

问题


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.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/5278322/regular-expression-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!