wyc
wyc

Reputation: 55273

How to prevent matching single quotes that have white space on their right?

The following regex is made to match single quotes that should be replaced by smart right single quote ( ’ ):

enter image description here

It works. But as you can see, it shouldn't match the one in '*text*. So I modified the regex:

(\S)'(?!\b)|(?=\b)'(?=\b)

The problem now is that it's not only matching the quotes but the other punctuation too:

enter image description here

I'm not a regex expert so I'm not sure how to do it so that only the single quotes are matched in the new regex.

Upvotes: 0

Views: 60

Answers (2)

anubhava
anubhava

Reputation: 785058

You can use backreference of your captured group #1 in replacement to get back what you've matched using (\S):

var re = /(\S)'(?!\b)|(?=\b)'(?=\b)/g; 
var str = 'text, \'*text* text?\'\n*It\'s text couldn\'t I\'d text.\'*';

var result = str.replace(re, '$1’');

PS: Your regex can be shortened to:

/(\S)'\B|\b'\b/g

RegEx Demo

Upvotes: 1

Mariano
Mariano

Reputation: 6511

I may be misinterpreting your question, but I think you're trying to match a single quote if it's not preceded by a whitespace. The following regex uses a lookbehind to assert it's in a position preceded by \S (a non-whitespace character).

/(?<=\S)'/g

regex101 demo

Upvotes: 1

Related Questions