Reputation: 2326
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 )
"dd."
= match"d.d"
= matchAllowed Examples ( no match )
"d."
= no match " d."
= no match" d. "
= no match"d. "
= no matchThe 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
Reputation: 89547
You can solve the problem with a capturing group:
res = str.replace(/([^ ][a-z]|[^a-z]|^)\.|\.(?=[^ ])/g, '$1 ');
Upvotes: 1
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
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
Reputation: 43243
Perhaps you could use XRegExp, which adds support for negative lookbehinds (amongst other things)?
Upvotes: 2