Dyvel
Dyvel

Reputation: 987

Regex match line containing string

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

Upvotes: 47

Views: 137775

Answers (5)

Evandro Coan
Evandro Coan

Reputation: 9485

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.

Upvotes: 30

mkkabi
mkkabi

Reputation: 801

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

^.*substring.*$

Upvotes: 63

Leonardo Scotti
Leonardo Scotti

Reputation: 1080

Try this:

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

explaination:

( ... ) : groups and captures the line

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

.* : any characters

Upvotes: 8

bz9js
bz9js

Reputation: 21

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.

Upvotes: 2

Astrogat
Astrogat

Reputation: 1625

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).

Upvotes: 7

Related Questions