简体   繁体   English

仅匹配某些字符的正则表达式模式

[英]RegEx Pattern to Match Only Certain Characters

I'm a newbie to RegEx, and this particular issue is flummoxing me.我是 RegEx 的新手,这个特殊问题让我很困惑。 This is for use with a JavaScript function.这是与 JavaScript 函数一起使用的。

I need to validate an input so that it matches only these criteria:我需要验证输入,使其仅符合以下条件:

  • Letters AZ (upper and lowercase)字母 AZ(大写和小写)
  • Numbers 0-9数字 0-9
  • The following additional characters: space, period (.), comma (,), plus (+), and dash (-)以下附加字符:空格、句点 (.)、逗号 (,)、加号 (+) 和破折号 (-)

I can write a pattern easily enough for the first two criteria, but the third one is more difficult.对于前两个标准,我可以很容易地编写一个模式,但第三个标准更难。 This is the last pattern I managed, but it doesn't seem to work with the test string Farh%%$$+++,这是我管理的最后一个模式,但它似乎不适用于测试字符串Farh%%$$+++,

Here's the pattern I'm trying这是我正在尝试的模式

[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\\+\\.\\,\\s]*$ 

It's failing in that it's letting characters other than those specified in the text field when submitting the form.它的失败在于它在提交表单时允许文本字段中指定的字符以外的字符。

Any help would be greatly appreciated.任何帮助将不胜感激。

我刚刚对此进行了测试,它似乎至少在我的第一轮测试中有效。

^[a-zA-Z 0-9\.\,\+\-]*$

The dash needs to be first in order not to be interpreted as a range separator.破折号必须是第一个,以免被解释为范围分隔符。 Also, make sure you anchor your regex with a ^ and $ at the beginning and end respectively so that your entire test string gets swallowed by your regex.另外,请确保在开头和结尾分别使用 ^ 和 $ 锚定正则表达式,以便您的整个测试字符串被正则表达式吞没。

/^[-+., A-Za-z0-9]+$/
/^[a-z0-9 .,+-]+$/i

For validate selector as ID only (according to allowed characters https://www.w3.org/TR/html4/types.html#type-id ):仅将选择器验证为 ID(根据允许的字符https://www.w3.org/TR/html4/types.html#type-id ):

var isValidIdSelector = function (str) {
    var regex = new RegExp(/^[A-Za-z][A-Za-z0-9_\-\:\.]*$/gm);
    return regex.test(str);
};
ng-pattern="/^[a-zA-Z0-9/&quot&quot\\\]\[:;|=,+*?<>]+$/"

允许:字母数字 + " / \\ [ ] : ; | = , + * ? <>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM