正则表达式-必须包含字母数字和斜杠 [英] REGEX - must contain alphanumeric and slash
问题描述
我正在尝试验证输入字段必须包含字母数字和斜杠作为其值.
I am trying to do a validation that an input field must contain alpha numeric and slash as its value.
例如:AA/AB/12314/2017/ASD
Eg: AA/AB/12314/2017/ASD
上面显示的是应作为输入字段的值的示例. 我对编写正则表达式一无所知.所以请帮助我.
The above shown is the example of the value that should be the input field. I don't have any knowledge in writing the regular expressions. So please do help me.
最后我想出了以下代码:
Finally I came up with the below code:
var message = $('#message').val();
if (/^[a-zA-Z0-9-/]*$/.test($.trim(message)) == false)
{
$('#message').focus();
alert('invalid message');
}
推荐答案
它必须同时包含字母数字和斜杠.
it must contain both alphanumeric and slash.
我了解您可能有1+个字母数字符号,后跟至少1个/
,后跟更多字母数字符号.您需要将正则表达式更改为/^[a-z\d]+(?:\/[a-z\d]+)+$/i
:
I understand that you may have 1+ alphanumeric symbols followed with at least 1 /
followed with more alphanumeric symbols. You need to change the regex to /^[a-z\d]+(?:\/[a-z\d]+)+$/i
:
var message = $('#message').val();
if (!/^[a-z\d]+(?:\/[a-z\d]+)+$/i.test($.trim(message)))
{
$('#message').focus();
alert('invalid message');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="message" value="ASD/TD"/>
详细信息:
-
^
-字符串开头 -
[a-z\d]+
-1个或多个字母或数字 -
(?:\/[a-z\d]+)+
-1个或多个序列-
\/
-斜杠 -
[a-z\d]+
-1个或多个字母或数字
^
- start of string[a-z\d]+
- 1 or more letters or digits(?:\/[a-z\d]+)+
- 1 or more sequences of\/
- slash[a-z\d]+
- 1 or more letters or digits
如果您的意思是字符串中必须在任意位置包含
/
和字母数字 ,请使用前行:If you mean there must be a
/
and alphanumeric anywhere inside the string, use lookaheads:/^(?=[a-z\d]*\/)(?=\/*[a-z\d])[a-z\d\/]+$/i ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
请参见 regex演示.此处,
(?=[a-z\d]*\/)
在0+字母数字后需要/
,而(?=\/*[a-z\d])
在0+斜杠后需要字母数字.[a-z\d\/]+
将匹配1个或多个字母数字或斜杠.See the regex demo. Here,
(?=[a-z\d]*\/)
requires a/
after 0+ alphanumerics, and(?=\/*[a-z\d])
requires an alphanumeric after 0+ slashes.[a-z\d\/]+
will match 1 or more alphanumeric or slashes.这篇关于正则表达式-必须包含字母数字和斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-