Java 中的正则表达式将字母数字作为输入,后跟正斜杠,然后再输入字母数字
我需要一个正则表达式,它接受字母数字作为输入,后跟正斜杠,然后再次输入字母数字。我如何在Java中为此编写正则表达式?
示例如下:
adc9/fer4
我尝试使用正则表达式如下:
String s = abc9/ferg5;
String pattern="^[a-zA-Z0-9_]+/[a-zA-z0-9_]*$";
if(s.matches(pattern))
{
return true;
}
但问题是它接受 abc9/ 形式的所有字符串,而不在正斜杠后进行检查。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
参考: http://download.oracle .com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
希望这会有所帮助。
Reference: http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
Hope this helps.
我会使用:
[a-zA-Z0-9] 允许任何字母数字字符串
+ 是一个或多个
([a-zA-Z0-9]+) 表示存储该组的值
$1 表示召回第一组
I would use:
[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
这是模拟
\w
含义所需的 Java 代码:现在,在模式中只要需要一个
\w
字符,就使用identifier_charclass
,并且 < code>not_identifier_charclass 无论您需要一个\W
字符。它并不完全符合标准,但它比 Java 的不完善的定义要好得多。This is the Java code needed to emulate what
\w
means:Now use
identifier_charclass
in a pattern wherever you want one\w
character, andnot_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.星号应该是一个加号。在正则表达式中,星号表示 0 个或多个; plus表示1或更多。您在斜杠之前的部分后面使用了加号。您还应该在斜杠后面的部分使用加号。
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.
我认为最短的Java正则表达式可以做我认为你想要的事情是
“^\\w+/\\w+$”
。I think the shortest Java regular expression that will do what I think you want is
"^\\w+/\\w+$"
.