Regex to match only letters

后端 未结 20 1535
孤城傲影
孤城傲影 2020-11-22 16:24

How can I write a regex that matches only letters?

相关标签:
20条回答
  • 2020-11-22 16:38
    /[a-zA-Z]+/
    

    Super simple example. Regular expressions are extremely easy to find online.

    http://www.regular-expressions.info/reference.html

    0 讨论(0)
  • 2020-11-22 16:41

    If you mean any letters in any character encoding, then a good approach might be to delete non-letters like spaces \s, digits \d, and other special characters like:

    [!@#\$%\^&\*\(\)\[\]:;'",\. ...more special chars... ]
    

    Or use negation of above negation to directly describe any letters:

    \S \D and [^  ..special chars..]
    

    Pros:

    • Works with all regex flavors.
    • Easy to write, sometimes save lots of time.

    Cons:

    • Long, sometimes not perfect, but character encoding can be broken as well.
    0 讨论(0)
  • 2020-11-22 16:41
    /^[A-z]+$/.test('asd')
    // true
    
    /^[A-z]+$/.test('asd0')
    // false
    
    /^[A-z]+$/.test('0asd')
    // false
    
    0 讨论(0)
  • 2020-11-22 16:41

    pattern = /[a-zA-Z]/

    puts "[a-zA-Z]: #{pattern.match("mine blossom")}" OK

    puts "[a-zA-Z]: #{pattern.match("456")}"

    puts "[a-zA-Z]: #{pattern.match("")}"

    puts "[a-zA-Z]: #{pattern.match("#$%^&*")}"

    puts "[a-zA-Z]: #{pattern.match("#$%^&*A")}" OK

    0 讨论(0)
  • 2020-11-22 16:42

    Depending on your meaning of "character":

    [A-Za-z] - all letters (uppercase and lowercase)

    [^0-9] - all non-digit characters

    0 讨论(0)
  • 2020-11-22 16:42

    JavaScript

    If you want to return matched letters:

    ('Example 123').match(/[A-Z]/gi) // Result: ["E", "x", "a", "m", "p", "l", "e"]

    If you want to replace matched letters with stars ('*') for example:

    ('Example 123').replace(/[A-Z]/gi, '*') //Result: "****** 123"*

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