spencer.sm
spencer.sm

Reputation: 20634

Match part of string not proceeded by a space

How can I match a substring only if it is not proceeded by a space?

In the string below, I want to match only the first and third lines and not the second. In this case the line also needs to start with a #

#match
 #not match
#match

https://regex101.com/r/VE3Q8z/1

The negative lookahead (?! ) doesn't seem to affect anything. Maybe what I'm looking for is a negative look-behind, but I haven't found any examples (that make sense to me) on how do do so in Javascript.

Upvotes: 0

Views: 36

Answers (3)

Mattasse
Mattasse

Reputation: 1171

This is your regex :

^#(.*)

this part ^# match with all string that begin by #. You can modify the last part to match only character or number..

Upvotes: 1

Jan
Jan

Reputation: 43199

You could achieve it with anchors:

^(?! )(#+)(.*)

See the afore-mentionned link to your own demo: https://regex101.com/r/VE3Q8z/2

Upvotes: 3

Fueled By Coffee
Fueled By Coffee

Reputation: 2569

Just use an anchor to verify that the string starts with a "#". And then add the "global" and "multiline" flags to it

/^#+(.*)/gm

https://regex101.com/r/koOXUB/1

Upvotes: 1

Related Questions