Spock
Spock

Reputation: 33

Regex - Exclude a match if it is preceeded by a specific character

I am attempting to parse a string and return the stuff between the #, but only if the # is not preceded by a \.

For example, I was messing around with the following test string on regexr.com:

This is a #date# test.

Using #.*# I'm able to retrieve the test I want. However, give this string:

This is a \#date# test.

I don't want it to return as the backslash is in front of the #. Thus far, I've come up with:

[^\\](#.*.#)

However, when a backslash isn't present in the test string, it ends up grabbing whichever character is in front of the #. Is there any way to grab just the "#date#" part from the test string but only if it is not preceded by a blackslash?

Upvotes: 3

Views: 300

Answers (2)

hwnd
hwnd

Reputation: 70750

You can use the following regular expression.

\\#|#(.*?)#

Note: You can access your match result from capturing group #1

Live Demo

Upvotes: 2

Federico Piazza
Federico Piazza

Reputation: 31035

You can use regex lookbehind for your case.

You can use this regex:

(?<!\\)#(.*?)#

Working demo

enter image description here

Upvotes: 3

Related Questions