Regex help with matching
Hello I need coming up with a valid regular expression It could be any identifier name that starts with a letter or underscore but may contain any number of lett开发者_StackOverflow社区ers, underscores, and/or digits (all letters may be upper or lower case). For example, your regular expression should match the following text strings: “_”, “x2”, and “This_is_valid” It should not match these text strings: “2days”, or “invalid_variable%”.
So far this is what I have came up with but I don't think it is right
/^[_\w][^\W]+/
The following will work:
/^[_a-zA-Z]\w*$/
Starts with (^
) a letter (upper or lowercase) or underscore ([_a-zA-Z]
), followed by any amount of letter, digit, or underscore (\w
) to the end ($
)
Read more about Regular Expressions in Perl
Maybe the below regex:
^[a-zA-Z_]\w*$
If the identify is at the start of a string, then it's easy
/^(_|[a-zA-Z]).*/
If it's embedded in a longer string, I guess it's not much worse, assuming it's the start of a word...
/\s(_|[a-zA-Z]).*/
精彩评论