[英]Javascript regex to match words separated by a spaced delimiter
I would like to validate an input of words separated by some delimiter. 我想验证由某些定界符分隔的单词的输入。 The delimiter in this case is the "|"
在这种情况下,分隔符是“ |” sign, separated by space before and after
标志,前后用空格隔开
Hello | There | Yes -----> Match
Hello -----> Match
hello|There -----> No Match
So far I've gotten to only the first word with the following rejex: 到目前为止,我只剩下第一个单词,但有以下几点反对:
^[a-zA-Z]+
how do I separate the words or numbers with a space and a delimiter? 如何用空格和定界符分隔单词或数字? PS Still working through the tutorials.
PS仍在学习教程。 Any help would be appreciated
任何帮助,将不胜感激
To Further clarify, i'm looking for regex for the above for a dojo dijit widget to validate the input properly. 为了进一步阐明,我正在为dojo dijit小部件寻找以上的正则表达式,以正确验证输入。
dojo.declare("some.class", dijit.form.ValidationTextBox, {
regExp: ""
});
dojo.addOnLoad(function() {
var formString = new some.class({
}, "StringName");
}
<form id="myForm" name="myForm">
String: <input id="StringName" name="name" type="text">
</form>
If you know it will always be one space followed by a pipe character followed by one space, it is probably easier to use split()
without a regexp. 如果您知道它将始终是一个空格,然后是管道字符,然后是一个空格,那么使用不带正则表达式的
split()
可能会更容易。
var myArray = myString.split(' | ');
If you absolutely must use a regexp because (for example) you don't know what kind of whitespace character or how many there will be, you can still use split()
but just pass it the regexp: 如果您绝对必须使用正则表达式,因为(例如)您不知道哪种空白字符或将有多少个空白字符,您仍然可以使用
split()
,只需将其传递给正则表达式即可:
var myRegExp = /\s+\|\s+/;
var myArray = myString.split(myRegExp);
If you want to use a regex, you can use a simple regex like this: 如果要使用正则表达式,可以使用一个简单的正则表达式,如下所示:
^\w+(?:\s\|\s\w+)*$ <--- this allows a unique word
or
^\w+(?:\s\|\s\w+)+$ <--- this allows two words at least
Javascript code: JavaScript代码:
var re = /^\w+(?:\s\|\s\w+)*$/gm;
var str = 'Hello | There | Yes\nhello|There\n456 | 654 | 645 | 465';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Seems like you're trying to match the whole line if the line is of above mentioned format. 如果该行具有上述格式,似乎您正在尝试匹配整行。
^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)+$
OR 要么
Use this if you want to match a single word also. 如果您还想匹配单个单词,请使用此选项。
^[A-Za-z\d]+(?:\s\|\s[A-Za-z\d]+)*$
var s = "Hello | There | Yes"; var s1 = "hello|There"; var s2 = "456 | 654 | 645 | 465"; alert(/^[A-Za-z\\d]+(?:\\s\\|\\s[A-Za-z\\d]+)+$/.test(s)) alert(/^[A-Za-z\\d]+(?:\\s\\|\\s[A-Za-z\\d]+)+$/.test(s1)) alert(/^[A-Za-z\\d]+(?:\\s\\|\\s[A-Za-z\\d]+)+$/.test(s2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.