2

I am trying to match a stand alone s ignoring case. I do not want to match an s that is preceded by an apostrophe. My current regex is /\b[s]\b/ig and my test string is and the S on lines 2 and 3 should be the only matches.

Men's
S
Just S Things
Somethings

Regexr: http://regexr.com/3geo2

4castle
  • 32,613
  • 11
  • 69
  • 106
yourfavorite
  • 517
  • 8
  • 21
  • What you need is a negative lookbehind, but Javascript doesn't support it. A cheap way around is to reverse the string and do a negative lookahead instead. See [here](https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent) for example. – Matt Burland Jul 27 '17 at 21:05
  • You can try `\s+s\s+` – MaxZoom Jul 27 '17 at 21:21
  • @MaxZoom you submitted as a reply and not an answer but this seems to work for me! Toss it up as an answer so I can mark appropriately :D – yourfavorite Jul 27 '17 at 21:21
  • @MaxZoom You edited your first answer that was working. Your previous answer worked for me. `(^|\s)s($|\s)` – yourfavorite Jul 27 '17 at 21:23
  • I have posted it as the answer, thx – MaxZoom Jul 27 '17 at 21:25

2 Answers2

2

After a short experimentation I have came up with the following regex

(?:\s|^)s(?:\s|$)

DEMO

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
1

One trick you could use is to use alternation between a non-capturing and a capturing expression, and then in your post-processing of the regex matches, discard the matches that don't have a capture group.

The regex would be:

/'s|(\bs\b)/ig

And if you were using it to do replacement operations, it would be used like:

var str = "Men's\nS\nJust S Things\nSomethings";

var updatedStr = str.replace(/'s|(\bs\b)/ig,
  (match, captureGroup) => captureGroup ? "<S>" : match
);

console.log(updatedStr);
4castle
  • 32,613
  • 11
  • 69
  • 106