我想验证只有字母数字,撇号和点(。)的名称字段。例如,它应该允许字符串abc's home99
,St. Mary's Hospital
但我不希望字符串以字符串开头任何特殊字符或以其结尾,例如'abc
或abc'
或g_abc 56gfhg
或abc 56gfhg.
。
我用过
stringPattern = /^[a-zA-Z0-9']*$/;
模式但它允许在字符串中的任何位置使用撇号。
答案 0 :(得分:3)
答案 1 :(得分:2)
var pattern = /^[^'][a-zA-Z0-9' ]*[^']$/;
console.log(pattern.exec("abc's home99"));
console.log(pattern.exec("'abc"));
console.log(pattern.exec("abc'"));
<强>输出强>
[ 'abc\'s home99', index: 0, input: 'abc\'s home99' ]
null
null
在这个正则表达式中,我们说,第一个字符不应该是'
(^[^']
),最后一个字符不应该是'
([^']$
)。你已经完成了其余的事情:)
答案 2 :(得分:0)
我会这样做:
^\w+(?:[.' ]*\w+)*$
<强>解释强>
The regular expression:
^\w+(?:[.' ]*\w+)*$
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
----------------------------------------------------------------------
[.' ]* any character of: '.', ''', ' ' (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
\w+ word characters (a-z, A-Z, 0-9, _) (1 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
)* end of grouping
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
答案 3 :(得分:0)
在html输入元素的pattern属性中尝试[A-Z,a-z,0-9,` - &#39;,*]。它将允许字母,空格,数字,撇号和连字符。