47

I'm trying to create a regex that will select an entire line where it contains a matching string.

I can't seem to get it to work. Here is the expression:

^.*?(\bEventname 2\b).*$

You can see the test case and what I've tried here:

https://www.regex101.com/r/mT5rZ3/1

5
  • 2
    What about .*Eventname 2.*.
    – m0skit0
    Commented Jul 31, 2015 at 11:54
  • you forget to put m modifier. regex101.com/r/mT5rZ3/2 Commented Jul 31, 2015 at 11:57
  • @AvinashRaj Why add multi-line modifier if OP only wants to match single lines?
    – m0skit0
    Commented Jul 31, 2015 at 11:59
  • @AvinashRaj I see it working in regex101 but in my software (uBot Studio) it doesn't. Don't think I can use m modifier there, but thanks for the try :-)
    – Dyvel
    Commented Jul 31, 2015 at 12:01
  • Actually I got you solution @m0skit0 to work by first filtering my search string to only use the code in parenthesis as it was unique and made it easier to match... Thanks!
    – Dyvel
    Commented Jul 31, 2015 at 12:33

5 Answers 5

62

here's what I use and it works perfectly for me

^.*substring.*$
30

This answer solves the question with 463 steps instead of 952 steps. Just ensure a new line at the end of the file.

.*Eventname 2.*\n

https://www.regex101.com/r/mT5rZ3/5

EDIT 4-9-2022

With .*Eventname 2.*\n? it also solves with 463 steps, but there is no need to ensure a new line at the end of the file.

8

Try this:

(.*(?:Eventname 2).*)

explaination:

( ... ) : groups and captures the line

(?:...) : groups without capturing the string that the line needs to contain

.* : any characters

7

If you are using the PHP regex . don't match newlines. So

.*(\bEventname 2\b).*

would be enough. If . matches newline you would need *? to make the dots non-greedy (so it just matches one line, instead of everything). You also need to be in multi-line mode to use ^ and $, but that shouldn't be necessary (since you only want to match one line anyway).

2
  • My search string would be like: Eventname 2 (T104) - can't seem to get it to work like that... ?
    – Dyvel
    Commented Jul 31, 2015 at 12:11
  • .*(\bEventname 2 (T104)).* Skip the word boundry, since it's already ended with ). You also need to escape the ().
    – Astrogat
    Commented Jul 31, 2015 at 12:22
2

You are using a string containing several lines. By default, the ^ and $ operators will match the beginning and end of the whole string. The m modifier will cause them to match the beginning and end of a line.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.