Search code examples
rubyregexsubstitutionletters

How do I remove non-letters from the beginning of the string


I'm using Ruby 2.4. How do I remove non-letters from the beginning of my string? I thought I could do something like

name ? name.sub(/^[^a-z]*/i, "") : nil

but this neglects things like an accented a ("á") or that type of "u" with the dots above it.

I don't consider numbers or punctuation marks letters so I would want them removed from the beginning of my string.


Solution

  • You may match non-letters with a Unicode category class \P{L}:

    name = name.sub(/\A\P{L}+/, "")
    

    Pattern details:

    • \A - start of string anchor
    • \P{L}+ - one or more (+) characters other than letters (\P{L}).