Maximiliano Santa Cruz
Maximiliano Santa Cruz

Reputation: 401

Match start of a line or nothing using regex

I have the following in a configuration file:

property = 10
#property = 10
#this is a test for #property
#this is a test for property

And I'm trying to come up with a regex to match only the first 2 cases:

property = 10 //this one
#property = 10 //and this one
#this is a test for #property
#this is a test for property

So far, what I did was:

#property.*|^property.*

And this is the result:

enter image description here

I tried other variants, but the results change for the worst:

^#property.*|^property.*
[^\s]#property.*|^property.*

Here's the link of the online regex that I'm using:

https://regex101.com/r/K2tm75/2

I will use this regex in a grep command as part of a bash script.

Upvotes: 1

Views: 275

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You need to make sure you match #property or property at the start of the string.

I suggest

^#?property.*

or - to only match them with = and digits at the end:

^#?property *= *[0-9]+$

See the regex demo 1 and regex demo 2.

The ^#?property.* matches the start of the input, then an optional # (#? matches 1 or 0 occurrences, then property and then any 0+ chars).

The second pattern - ^#?property *= *[0-9]+$ - matches a similar beginning, but, after property, matches zero or more spaces, =, zero or more spaces and then 1+ digits and the end of string (with $).

Upvotes: 2

Related Questions