Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match pattern anywhere in string?

Tags:

regex

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?

like image 912
En-Motion Avatar asked Aug 13 '14 13:08

En-Motion


People also ask

How do you match a string to a pattern?

To match a character in the string expression against a range of characters. Put brackets ( [ ] ) in the pattern string, and inside the brackets put the lowest and highest characters in the range, separated by a hyphen ( – ). Any single character within the range makes a successful match.

How do I match a pattern in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does (? I do in regex?

E.g. (? i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode.


2 Answers

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.

like image 22
Charles Avatar answered Sep 29 '22 01:09

Charles


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
like image 90
branch14 Avatar answered Sep 29 '22 01:09

branch14