Regex, every non-alphanumeric character except white space or colon

前端 未结 9 1988
醉梦人生
醉梦人生 2020-11-27 11:23

How can I do this one anywhere?

Basically, I am trying to match all kinds of miscellaneous characters such as ampersands, semicolons, dollar signs, etc.

相关标签:
9条回答
  • 2020-11-27 11:50

    Try to add this:

    ^[^a-zA-Z\d\s:]*$
    

    This has worked for me... :)

    0 讨论(0)
  • 2020-11-27 11:55

    If you want to treat accented latin characters (eg. à Ñ) as normal letters (ie. avoid matching them too), you'll also need to include the appropriate Unicode range (\u00C0-\u00FF) in your regex, so it would look like this:

    /[^a-zA-Z\d\s:\u00C0-\u00FF]/g
    
    • ^ negates what follows
    • a-zA-Z matches upper and lower case letters
    • \d matches digits
    • \s matches white space (if you only want to match spaces, replace this with a space)
    • : matches a colon
    • \u00C0-\u00FF matches the Unicode range for accented latin characters.

    nb. Unicode range matching might not work for all regex engines, but the above certainly works in Javascript (as seen in this pen on Codepen).

    nb2. If you're not bothered about matching underscores, you could replace a-zA-Z\d with \w, which matches letters, digits, and underscores.

    0 讨论(0)
  • 2020-11-27 11:55

    In JavaScript:

    /[^\w_]/g

    ^ negation, i.e. select anything not in the following set

    \w any word character (i.e. any alphanumeric character, plus underscore)

    _ negate the underscore, as it's considered a 'word' character

    Usage example - const nonAlphaNumericChars = /[^\w_]/g;

    0 讨论(0)
  • 2020-11-27 11:59

    Try this:

    [^a-zA-Z0-9 :]
    

    JavaScript example:

    "!@#$%* ABC def:123".replace(/[^a-zA-Z0-9 :]/g, ".")
    

    See a online example:

    http://jsfiddle.net/vhMy8/

    0 讨论(0)
  • 2020-11-27 12:00
    [^a-zA-Z\d\s:]
    
    • \d - numeric class
    • \s - whitespace
    • a-zA-Z - matches all the letters
    • ^ - negates them all - so you get - non numeric chars, non spaces and non colons
    0 讨论(0)
  • 2020-11-27 12:03

    No alphanumeric, white space or '_'.

    var reg = /[^\w\s)]|[_]/g;
    
    0 讨论(0)
提交回复
热议问题