Steffan Harris
Steffan Harris

Reputation: 9326

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 letters, 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]+/

Upvotes: 3

Views: 96

Answers (3)

David Fells
David Fells

Reputation: 6798

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

Upvotes: 0

manojlds
manojlds

Reputation: 301147

Maybe the below regex:

^[a-zA-Z_]\w*$

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72971

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

Upvotes: 2

Related Questions