开发者

What is the best way to match only letters in a regex?

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


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


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


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


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.


[^\W0-9_]

# or

[[:alpha:]]

See perldoc perlre


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)


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜