123Developer
123Developer

Reputation: 1493

Regular expression to analyze escape character?

I want to analyze escape character in my using regex.

For example the regex pattern should match if the string contains character (a) in it but it should not match if the character a is preceded by an apostrophe ('a)

eg:

"a" - true, "aba" - true, "car" - true, "foo" - false, "c'ar" - false

Thanks.

Upvotes: 0

Views: 84

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

Use negative lookbehind to match only as not preceded by 's.

(?<!')a

Warning: some flavors of regex (JavaScript, Ruby, Tcl) do not support lookbehind.

I would like to have the solution to run in Javascript

Then I will refer you to my boilerplate reference: Mimicking Lookbehind in JavaScript. Alternately, just scan the string yourself, without using regex. This is a pretty easy one, and is quite possibly faster than any lookbehind-mimicking version.

function matches_a_not_preceded_by_apos(str)
{
    var found_an_a = false;
    for (var i=1; i<str.length; i++)
    {

        if (str.charAt(i) === "a")
        {
            found_an_a = true;
            if (str.charAt(i-1) === "'")
            {
                return false;
            }
        }
    }
    return found_an_a;
}

Upvotes: 1

Sina Iravanian
Sina Iravanian

Reputation: 16286

You can use this pattern:

(?<!\')a

And this is the demo: http://regexr.com?33mue

(?<!\') is the negative look-behind, which says match a if it is not preceded by \'.

Upvotes: 0

Related Questions