allow parentheses and other symbols in regex

前端 未结 5 990
醉话见心
醉话见心 2020-12-15 14:18

I\'ve made this regex:

^[a-zA-Z0-9_.-]*$

Supports:

letters [uppercase and lowercase]
numbers [from 0 to 9]
underscores [_]
         


        
相关标签:
5条回答
  • 2020-12-15 14:30

    Inside of a character class [...] the hyphen - has a special meaning unless it is the first or last character, so you need to escape it:

    ^[a-zA-Z0-9 _.,\-!()+=“”„@"$#%*]*$
    

    None of the other characters need to be escaped in the character class (except ]). You will also need to escape the quote indicating the string. e.g.

    '/[\']/'
    "/[\"]/"
    
    0 讨论(0)
  • 2020-12-15 14:35

    The hyphen is being treated as a range marker -- when it sees ,-! it thinks you're asking for a range all characters in the charset that fall between , and ! (ie the same way that A-Z works. This isn't what you want.

    Either make sure the hyphen is the last character in the character class, as it was before, or escape it with a backslash.

    I would also point out that the quote characters you're using “”„ are part of an extended charset, and are not the same as the basic ASCII quotes "'. You may want to include both sets in your pattern. If you do need to include the non-ASCII characters in the pattern, you should also add the u modifier after the end of your pattern so it correctly picks up unicode characters.

    0 讨论(0)
  • 2020-12-15 14:44

    Make sure to put hyphen - either at start or at end in character class otherwise it needs to be escaped. Try this regex:

    ^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]*$
    

    Also note that because * it will even match an empty string. If you don't want to match empty strings then use +:

    ^[a-zA-Z0-9 _.,!()+=`,"@$#%*-]+$
    

    Or better:

    ^[\w .,!()+=`,"@$#%*-]+$
    

    TEST:

    $text = "_.,!()+=,@$#%*-";
    if(!preg_match('/\A[\w .,!()+=`,"@$#%*-]+\z/', $text)) {
       echo "error.";
    }
    else {
       echo "OK.";
    }
    

    Prints:

    OK.
    
    0 讨论(0)
  • 2020-12-15 14:47

    try this

    ^[A-Z0-9][A-Z0-9*&!_^%$#!~@,=+,./\|}{)(~`?][;:\'""-]{0,8}$

    use this link to test

    trick is i reverse ordered the parenthesis and other braces that took care of some problems. And for square braces you must escape them

    0 讨论(0)
  • 2020-12-15 14:50

    Try escaping your regex: [a-zA-Z0-9\-\(\)\*]

    Check if this help you: How to escape regular expression special characters using javascript?

    0 讨论(0)
提交回复
热议问题