What is the best way to match only letters in a re

2019-04-04 07:07发布

问题:

I would really like to use \w but it also matches underscores so I'm going with [A-Za-z] which feels unnecessarily verbose and America centric. Is there a better way to do this? Something like [\w^_] (I doubt I got that syntax right)?

回答1:

You could use /[a-z]/i or /[[:alpha:]]/ just as well. In fact, \w includes numbers so that won't even work.



回答2:

Perhaps you mean /[[:alpha:]]/? See perlre for the discussion of POSIX character classes.



回答3:

Just use \p{L} which means "any Unicode letter" and works in Perl (/\p{L}/). You probably need to use utf8;.



回答4:

Matching international (i.e non-ASCII) characters is kind of tough, and could depend on a lot of things. Check out this example:

#!perl -w

use strict;
use utf8;

my $string = "ä";

print "matched :alpha:\n"  if $string =~ /[[:alpha:]]/;
print "matched ^\\W0-9_\n" if $string =~ /[^\W0-9_]/;
print "matched [a-zA-Z]\n" if $string =~ /[a-zA-Z]/;
print "matched [a-z]i\n"   if $string =~ /[a-z]/i;
print "matched [A-z]\n"    if $string =~ /[A-z]/;

For me this results in

matched :alpha:

If you remove the use utf8 then none of the regular expressions match.

Looking at this very relevant question, it looks like you probably want to use utf8 and check out Unicode::Semantics.

Of course, if you're using straight ASCII characters than any of the aforementioned regular expressions will work.



回答5:

[^\W0-9_]

# or

[[:alpha:]]

See perldoc perlre



回答6:

A few options:

1. /[a-z]/i               # case insensitive
2. /[A-Z]/i               # case insensitive
3. /[A-z]/                # explicit range listing (capital 'A' to lowercase 'z')
4. /[[:alpha:]]/          # POSIX alpha character class

I recommend using either the case-insensitive, or the true way /[a-zA-z]/, unless you have a certain language preference in mind.

Note:

  • Number 3 requires the capital 'A' first and then lowercase 'z' because of the order of the ASCII values; it does not work if you do the reverse: a-Z. Also: this method would fail the no-underscore criteria, since it includes [ \ ] ^ _ ` .
  • Number 4 will match on those additional language characters, but it also matches on:
    ʹʺʻˍˎˏːˑˬˮ̀́   (plus many others)


回答7:

you're looking for internationalization in your regex? then you'll need to do something like this guy did: JavaScript validation issue with international characters

explicitly match on all of the moon language letters :)