Ronald
Ronald

Reputation: 16383

How to match up to second letter using regex?

How would I match "22A00" in the following string: "22A00B20A" using a regular expression?

Upvotes: 0

Views: 1749

Answers (2)

Mark Byers
Mark Byers

Reputation: 838416

You can use this:

/^[^a-zA-Z]*[a-zA-Z][^a-zA-Z]*/

Explanation:

^          Start of line
[^a-zA-Z]* Zero or more non-letters
[a-zA-Z]   A letter
[^a-zA-Z]* Zero or more non-letters

Regular expressions are greedy by default so this ensure that it will find the longest match. If there is no second letter it will match the entire string. If there is no first letter it will fail to match. If this isn't what you want then please specify what should happen in these special cases.

You may also want to consider what you mean by "letter". This regular expression won't match foreign letters.

Upvotes: 6

µBio
µBio

Reputation: 10748

If you are talking about that literal string

if( /22A00/.test("22A00B20A") )
    // match

otherwise, look to @Marks answer

Upvotes: 1

Related Questions