我需要一个正则表达式,它将字母数字作为输入,后跟正斜杠,然后再输入字母数字。我如何为此在Java中编写正则表达式?
示例如下:
adc9/fer4
我尝试使用正则表达式如下:
String s = abc9/ferg5;
String pattern="^[a-zA-Z0-9_]+/[a-zA-z0-9_]*$";
if(s.matches(pattern))
{
return true;
}
但问题是它接受所有形式 abc9/ 的字符串而不在正斜杠后检查。
我需要一个正则表达式,它将字母数字作为输入,后跟正斜杠,然后再输入字母数字。我如何为此在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);
希望这可以帮助。
我认为最短的 Java 正则表达式会做我认为你想要的"^\\w+/\\w+$"
。
我会使用:
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 表示调用第一组
这是模拟含义所需的 Java 代码\w
:
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 或更多;plus 表示 1 或更多。您在斜线之前的部分之后使用了加号。您还应该对斜线后的部分使用加号。