donguy76
donguy76

Reputation: 640

Find starting character(s) in a String

I am new to RegEx and need to come up with a RegEx that will find matching character(s) in a String.

The possible strings that i could get are:

DFG2344KG
4GGRTE
7TTRRE
T89FGFGD

So what i want is a RegEx that will check to see if the string starts with DFG or 4 or 7 or T

I came up with the following.

^[DFG|T|7|4]

The problem with above RegEx is, even if the string starts with F or G it will consider it to match, rather than looking for all characters like DFG.

Upvotes: 0

Views: 47

Answers (3)

sjagr
sjagr

Reputation: 16502

Use the group construct, not the range:

^(DFG|T|7|4)

Upvotes: 3

Barmar
Barmar

Reputation: 782130

You're confusing [] with (). [xyz] matches a single character that's either x, y, or z. (abc|def|ghi) matches either abc, def, or ghi. So it should be:

^(DFG|[T47])

Upvotes: 3

Brad Christie
Brad Christie

Reputation: 101614

Classes [] are for include characters (singular). What you're trying is looking for a D, F or G (not those in succession). You want something like:

^(DFG|T|7|4)

The pipe (|) alternates between the options. Also, given the 2nd, 3rd and 4th option are singular characters you can use a class within a group. e.g.

^(DEF|[T74])

Both perform the same comparison.

more info:

Upvotes: 1

Related Questions