我需要一个正则表达式,其输入字母和数字后接正斜杠,然后再输入字母数字。如何为此用Java写正则表达式?
示例如下:
adc9/fer4
我尝试使用正则表达式,如下所示:
String s = abc9/ferg5;
String pattern="^[a-zA-Z0-9_]+/[a-zA-z0-9_]*$";
if(s.matches(pattern))
{
return true;
}
但是问题是它接受了所有格式为abc9 /的字符串,但不检查正斜杠。
参考: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);
希望这会有所帮助。
我会使用:
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]允许任何字母数字字符串+是一个或多个([a-zA-Z0-9] +)表示存储组的值$ 1表示记得第一组
这是模拟\w
表示所需的Java代码:
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 */
现在在需要一个identifier_charclass
字符的位置使用\w
,然后在想要一个not_identifier_charclass
字符的位置使用\W
。它不是完全符合标准,但是比Java的那些坏定义要好得多。
星号应为加号。在正则表达式中,星号表示0或更大;加表示1或更大。您在斜杠前的部分之后使用了加号。您还应该在斜杠后的部分使用加号。
我认为可以完成我认为想要的最短Java正则表达式为"^\\w+/\\w+$"
。