6

I want to a capture a string with this regex:

^([\d]_[a-z|A-Z]+_test)$

So it would capture something like: 1_mytest_test

However, if the string is within another string like:

results.1_mytest_test.=fail, more info

There is no match.

I thought the ^ and $ would demarcate the beginning and end of the string that I am looking for, right?

3
  • Remove ^ and $, and |. Commented Nov 2, 2015 at 16:55
  • Oh, wow but why is that? Commented Nov 2, 2015 at 16:55
  • \b\d_[a-zA-Z]+_test\b Commented Nov 2, 2015 at 16:55

1 Answer 1

9

You should remove the ^/$ anchors, and you need no | inside the character class if you do not need to match a literal | with the regex:

\d_[a-zA-Z]+_test

See regex demo

The ^ is a start of string anchor, and $ is an end of string anchor, thus, they "anchor" the string you match at its start and end.

As for |, a character class matches a single character. [a-zA-Z] matches 1 letter. No need in the alternation operator | here since it is treated literally (i.e. the [a-zA-Z|] will match | symbol in the input string).

Just FYI: in many cases, when you need something to be matched inside a larger string, you need to use word boundaries \b to match whole words:

\b\d_[a-zA-Z]+_test\b

However, people often have non-word characters in patterns, then you'd be safer with look-arounds (not sure your engine supports look-behind, but here is a version for, say, PCRE):

(?<!\w)\d_[a-zA-Z]+_test(?!\w)
Sign up to request clarification or add additional context in comments.

3 Comments

But doesn't the ^ and $ demarcate the beginning and end of string I want to match?
The caret (^) tells the regex engine to start looking for a digit (\d) at the beginning, and then match all subpatterns from left to right and the _test must be at the end of the string. Or a line, if you specify the /m (multiline) modifier.
I also added some more fun details :) Have a great day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.