开发者

Regex help with matching

开发者 https://www.devze.com 2023-03-07 16:39 出处:网络
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, underscore

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]).*/

0

精彩评论

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