Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为javascript有效性编写正则表达式_Javascript_Regex - Fatal编程技术网

如何为javascript有效性编写正则表达式

如何为javascript有效性编写正则表达式,javascript,regex,Javascript,Regex,所有这些值都是可接受的值 ^[A-Z0-9]*[ _][A-Z0-9]*$ space cannot be accepted either at the beginning or end. space cannot be accepted at all instead of the value. allow numbers and characters in the start and end. allow hyphens in the middle not mandatory 但当我输入

所有这些值都是可接受的值

^[A-Z0-9]*[ _][A-Z0-9]*$

space cannot be accepted either at the beginning or end.
space cannot be accepted  at all instead of the value.
allow numbers and characters in the start and end.
allow hyphens in the middle not mandatory

但当我输入ABC BCD时。它说这不是正确的匹配

12345
ABC-12345
MM 1.8.10
530715 HS 9JAXXX4100
020-59898
HLXU1234
[^]=不能以空格开头或结尾

[\w-.]+=允许的所有字符,或者在本例中为\w、连字符、空格和点

匹配项:
ABC BCD

我认为将正则表达式分为多个正则表达式更为清晰

^[^ ]([\w- \.]+)[^ ]$

我不是100%确定你的意思,因为在允许的示例中,你有

毫米1.8.10

它不符合您指定的规则集

这就是为什么我将模式基于您的示例值,这应该是可行的

^[A-Z0-9]+?:[.-][A-Z0-9]+{0,3}$

解释

^从字符串的开头开始匹配

[A-Z0-9]+匹配一个或多个大写字母数字字符,因此空值将失败

?:启动非捕获组,此组将允许一个分隔符后跟至少一个字母数字大写字符,这是必需的,因此该值必须以字母数字字符开头和结尾,并且分隔符仅允许在两者之间

[-]匹配一个空格、下划线、点或连字符

[A-Z0-9]+匹配一个或多个大写字母数字字符

关闭非捕获组

{0,3}这允许组匹配0次或最多3次

$匹配字符串的结尾

在最后一部分{0,3}$中,3只允许最多3个额外的大写字母数字字符分组(由空格、下划线、点或连字符分隔),您可以将3更改为您想要的任何数字,或将其删除以允许0或无限分组

示例脚本:

function validate (str) {
    if (/^\s|\s$/.test(str)) { // starts or ends with a space
        return false;
    }
    if (/^-|-$/.test(str)) { // starts or ends with a hyphen
        return false;
    }
    return /[\s\w-]+/.test(str); // ensure all valid characters and non-empty
}

当我输入ABC BCD时。它说在中间不正确的Matjor连字号不是强制性的,到底是可以还是不在中间?当我键入ABC BCD时,是否需要至少一个字符作为起始和结束部分。它说它与你的正则表达式匹配是不正确的。连字符或者空间可以在中间。字符或数字任何东西都可以启动。当然,你可以用[AZ-0-9+] +替换[\W-+] +,这取决于你的精度要求。
<script type="text/javascript">
var strings = [
    'ABC BCD',
    '12345',
    'ABC-12345',
    'MM 1.8.10',
    '530715 HS 9JAXXX4100',
    '020-59898',
    'HLXU1234'
]
var matches = '';
for(i = 0; i < strings.length; i++) {
    matches += i + ' : ' + strings[i].match(/^[A-Z0-9]+(?:[ _.-][A-Z0-9]+){0,3}$/) + '\n';
}
window.alert(matches);
</script>