Regex to match only letters

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

How can I write a regex that matches only letters?

相关标签:
20条回答
  • 2020-11-22 16:28

    You would use

    /[a-z]/gi
    

    []--checks for any characters between given inputs

    a-z---covers the entire alphabet

    g-----globally throughout the whole string

    i-----getting upper and lowercase

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

    Lately I have used this pattern in my forms to check names of people, containing letters, blanks and special characters like accent marks.

    pattern="[A-zÀ-ú\s]+"
    
    0 讨论(0)
  • 2020-11-22 16:29

    So, I've been reading a lot of the answers, and most of them don't take exceptions into account, like letters with accents or diaeresis (á, à, ä, etc.).

    I made a function in typescript that should be pretty much extrapolable to any language that can use RegExp. This is my personal implementation for my use case in typescript. What I basically did is add ranges of letters with each kind of symbol that I wanted to add. I also converted the char to upper case before applying the RegExp, which saves me some work.

    function isLetter(char: string): boolean {
      return char.toUpperCase().match('[A-ZÀ-ÚÄ-Ü\s]+') !== null;
    }
    

    If you want to add another range of letters with another kind of accent, just add it to the regex. Same goes for special symbols.

    I implemented this function with TDD and I can confirm this works with, at least, the following cases:

        character | isLetter
        ${'A'}    | ${true}
        ${'e'}    | ${true}
        ${'Á'}    | ${true}
        ${'ü'}    | ${true}
        ${'ù'}    | ${true}
        ${'û'}    | ${true}
        ${'('}    | ${false}
        ${'^'}    | ${false}
        ${"'"}    | ${false}
        ${'`'}    | ${false}
    
    0 讨论(0)
  • 2020-11-22 16:34

    \p{L} matches anything that is a Unicode letter if you're interested in alphabets beyond the Latin one

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

    Use character groups

    \D
    

    Matches any character except digits 0-9

    ^\D+$
    

    See example here

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

    The closest option available is

    [\u\l]+
    

    which matches a sequence of uppercase and lowercase letters. However, it is not supported by all editors/languages, so it is probably safer to use

    [a-zA-Z]+
    

    as other users suggest

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