我需要使用以下条件创建一个正则表达式模式:
我创建了一个不允许提到的特殊字符以及空格的其他特殊字符。如何在中间而不是开始之间允许提到的字符。以下是我写的内容:
var string='Incharge';
var a= RegExp(/^[a-zA-Z0-9-:%/\\()\u2122.+\s]+$/).test(string);
console.log(a);
我的要求:
string='In-charge' -> Correct
string='Incharge' -> Correct
string='In charge' -> Correct
string='-In-charge' -> In Correct
string='--In-charge' -> In Correct
string=' In-charge' -> Correct
string=' a' -> Correct
string='in-charge' -> Correct
string='in-:charge' -> In Correct
string=' in- ' -> Correct
string='in@charge' -> In Correct
我试图适应所有条件,但无法做到。有人可以帮我吗?
采用
/^[a-zA-Z0-9\s]+(?:[-:%/\\()\u2122.+][a-zA-Z0-9\s]+)*$/
见证明。
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-zA-Z0-9\s]+ any character of: 'a' to 'z', 'A' to 'Z',
'0' to '9', whitespace (\n, \r, \t, \f,
and " ") (1 or more times (matching the
most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[-:%/\\()\u2122.+] any character of: '-', ':', '%', '/',
'\\', '(', ')', 'TM', '.', '+'
--------------------------------------------------------------------------------
[a-zA-Z0-9\s]+ any character of: 'a' to 'z', 'A' to
'Z', '0' to '9', whitespace (\n, \r, \t,
\f, and " ") (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
JavaScript:
const valid_strings = ['In-charge','Incharge','In charge',' In-charge',' a','in-charge',' in- '];
const invalid_strings = ['-In-charge','--In-charge','in-:charge','in@charge '];
const regex = /^[a-zA-Z0-9\s]+(?:[-:%/\\()\u2122.+][a-zA-Z0-9\s]+)*$/;
valid_strings.forEach(x => console.log(x, '(must be true) =>', regex.test(x)));
invalid_strings.forEach(x => console.log(x, '(must be false) =>', regex.test(x)));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句