简体   繁体   中英

RegEx Pattern to Match Only Certain Characters

I'm a newbie to RegEx, and this particular issue is flummoxing me. This is for use with a JavaScript function.

I need to validate an input so that it matches only these criteria:

  • Letters AZ (upper and lowercase)
  • Numbers 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%%$$+++,

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 ):

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\\\]\[:;|=,+*?<>]+$/"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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