正则表达式Javascript转义特殊字符加字符数限制

时间:2019-01-21 06:08:38

标签: javascript regex

有人可以帮助我使用此正则表达式吗?我需要一些允许的东西: 0-9 a-z A-Z 用逗号连字符撇号和其他特殊字符隔开:_ @ =。 加上同时设置字符数限制。

我现在有了这个,但是它抛出了无效的正则表达式异常。

var regex = /^\s*([0-9a-zA-Z\s\,\-\(\)\'\_\@\~\&\*\=\.\`]{1,35}+)\s*$/;
        return this.optional(element) || value.match(regex);
       }, "Please enter a valid name"    );

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

+之后删除{1,35},仅转义特殊字符:

var regex = /^\s*([0-9a-zA-Z\s,\-()'_@~&*=.`]{1,35})\s*$/;

console.log(regex.test(" asdfghjkl "))
console.log(regex.test(" asdf'&@() "))
console.log(regex.test(" asdfghjklasdfghjklasdfghjklasdfghjklasdfghjkl "))

答案 1 :(得分:0)

任何元序列组合

您似乎想要任何东西。如果是这样,请使用:

/[\S\s]{1,35}/g

括号[ ... ]表示其中一个字符是一个匹配项。

\s是任意空格。

\S是任何非空格。

{1,35}表示其前面的内容连续进行1到35个匹配。

演示

提供了获取前1到35个字符以及每1到35个字符的方法

var str = `1234567~!@#$%^&*e()_+_{}{:>><rthjokyuym.,iul[.<>LOI*&^%$#@!@#$%^&*()_+_{}{:>><KJHBGNJMKL>|}{POIUY~!@#$%^&*(+_)O(IU`;

var rgx = /[\s\S]{1,35}/g;

var res = rgx.exec(str);

console.log(`==== The first 35 characters ===========================`);
console.log(res[0]);
console.log(' ');
console.log(`==== OR for every 1 to 35 characters ===================`);
while (res !== null) {
  console.log(res[0]);
  var res = rgx.exec(str);
}
.as-console-wrapper {
  min-height: 100%;
}

div div div.as-console-row:first-of-type,
div div div.as-console-row:nth-of-type(4) {
  color: tomato
}

相关问题