Regex help matching

Hello, I need to find the correct regular expression. It can be any identifier name starting with a letter or underscore, but it can contain any number of letters, underscores and / or numbers (all letters can be in upper or lower case), For example, your regular expression should match the following text lines: " _ "," x2 "and" this_is_valid ". It must not match these text strings: "2days" or "invalid_variable%".

So far this is what I came up with, but I do not think it is right.

/^[_\w][^\W]+/
+3
source share
3 answers

The following will work:

/^[_a-zA-Z]\w*$/

(^) ( ) ([_a-zA-Z]), , (\w) ($)

Perl

+2

, :

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

If the identifier is at the beginning of the line, then easily

/^(_|[a-zA-Z]).*/

If it is embedded in a longer line, I think it is not much worse, assuming this is the beginning of the word ...

/\s(_|[a-zA-Z]).*/

0
source

All Articles