En-Motion
En-Motion

Reputation: 919

Match pattern anywhere in string?

I want to match the following pattern:

Exxxx49 (where x is a digit 0-9)

For example, E123449abcdefgh, abcdefE123449987654321 are both valid. I.e., I need to match the pattern anywhere in a string.

I am using:

^*E[0-9]{4}49*$

But it only matches E123449.

How can I allow any amount of characters in front or after the pattern?

Upvotes: 20

Views: 109801

Answers (5)

Charles
Charles

Reputation: 11479

Remove the ^ and $ to search anywhere in the string.

In your case the * are probably not what you intended; E[0-9]{4}49 should suffice. This will find an E, followed by four digits, followed by a 4 and a 9, anywhere in the string.

Upvotes: 21

branch14
branch14

Reputation: 1262

I would go for

^.*E[0-9]{4}49.*$

EDIT:

since it fullfills all requirements state by OP.

  • "[match] Exxxx49 (where x is digit 0-9)"
  • "allow for any amount of characters in front or after pattern"

It will match

  • ^.* everything from, including the beginning of the line
  • E[0-9]{4}49 the requested pattern
  • .*$ everthing after the pattern, including the the end of the line

Upvotes: 15

Unihedron
Unihedron

Reputation: 11041

Your original regex had a regex pattern syntax error at the first *. Fix it and change it to this:

.*E\d{4}49.*

This pattern is for matching in engines (most engines) that are anchored, like Java. Since you forgot to specify a language.

  • .* matches any number of sequences. As it surrounds the match, this will match the entire string as long as this match is located in the string.

Here is a regex demo!

Upvotes: 5

Braj
Braj

Reputation: 46841

How do I allow for any amount of characters in front or after pattern? but it only matches E123449

Use global flag /E\d{4}49/g if supported by the language

OR

Try with capturing groups (E\d{4}49)+ that is grouped by enclosing inside parenthesis (...)

Here is online demo

enter image description here

Upvotes: 1

Toto
Toto

Reputation: 91385

Just simply use this:

E[0-9]{4}49

Upvotes: 4

Related Questions