如何使用正则表达式模式限制字符串开头或结尾的特殊字符



我需要创建一个具有以下条件的正则表达式模式-

  1. 它可以有%[百分比],/[前斜杠],\[后斜杠],(([括号],™[商标]、+[plus]、–[连字符]、:[冒号]。它可以是单词、特殊字符和数字的组合
  2. 它可以允许像签入这样的单词,但不应该允许使用-:-%:
  3. 另外,字符串之间不能有两个特殊字符
  4. 它还可以允许字符串的开头、中间和结尾之间有空格
  5. 它也可以接受单个字符

我创建了一个不允许使用其他特殊字符的字符,除了提到的字符和空格。我如何允许在中间提到的字符,而不是在开头。以下是我写的:

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-9s]+(?:[-:%/\()u2122.+][a-zA-Z0-9s]+)*$/

见证明。

解释

--------------------------------------------------------------------------------
^                        the beginning of the string
--------------------------------------------------------------------------------
[a-zA-Z0-9s]+           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-9s]+           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-9s]+(?:[-:%/\()u2122.+][a-zA-Z0-9s]+)*$/;
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)));

相关内容

最新更新