Daniël de Wit
Daniël de Wit

Reputation: 2326

Negative lookbehind work around for 'simple' regular expression

I'm trying to get rid of excess dot characters in a string. ( JavaScript )

A dot is only allowed if it matches strict rules.

Allowed Rule: ( space or nothing)( 1 char a-z ).( space or nothing )

if any dot in the string does not match this, the dot must be replaced by a space (only the dot).

For example "" represents string start/end:

Illegal Examples ( MATCH )

Allowed Examples ( no match )

The closest I can get is:

var string = "dd. d.d d. d. d.d d.dd";

var res = string.replace(/[.](?! |$)/g, ' ');

Results in: "dd. d d d. d. d d d dd "

If JavaScript would support negative look behind I might be able to figure it out. Anyone have an idea how to match this correctly?

Upvotes: 1

Views: 581

Answers (4)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can solve the problem with a capturing group:

res = str.replace(/([^ ][a-z]|[^a-z]|^)\.|\.(?=[^ ])/g, '$1 ');

Upvotes: 1

brandonscript
brandonscript

Reputation: 72845

You might find it a lot simpler to replace ALL . with spaces, then re-parse your string and add dots back in where applicable?

Upvotes: 1

Phil H
Phil H

Reputation: 20131

To recreate lookbehind, reverse the string and use lookahead. If you need both, consider matching the lookahead on the forward string, and the lookbehind on the reverse string and find where the matches agree.

Alternatively, since the permitted case only has one occurrence of a dot, check whether the pattern matches, and do the string replacement if not.

if(!RegExp.test(string)) {
    string.replace(/[.]/g, ' ');
}

Upvotes: 1

Jani Hartikainen
Jani Hartikainen

Reputation: 43243

Perhaps you could use XRegExp, which adds support for negative lookbehinds (amongst other things)?

Upvotes: 2

Related Questions