0

I have a string as :

var str = "str is str, 12str345 and ABCstrDEF";

I want capture all str except ABCstrDEF (str surrounded by alphabetical characters)

Is it possible restrict alphabets with regex?

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
  • what about `ABCstr` or `strDEF` on its own? Also, what have you tried? – Martin Ender Oct 31 '12 at 15:51
  • Could you specify? do you want to capture `str` if it's a _"word"_ (not part of word): `.match(/\bstr\b/g)`, or if it's not preceded or followed by upper-case letters: `.match(/(?![A-Z])(str)(?![A-Z])/g)`, or is it an actual _alphabet_ string you want to exclude from your matches, as in `AXstrZY` is ok, but `ABstrCD` isn't? – Elias Van Ootegem Oct 31 '12 at 15:51
  • my goal is exclure all "str" which have any alphabet at left or right side –  Oct 31 '12 at 15:56

1 Answers1

2

Go with

RegExp.quote = function(str) {
  return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
};

var re = new RegExp("/\b[^a-zA-Z]*?" + RegExp.quote(str) + "[^a-zA-Z]*?\b/g");  
alert(input.match(re));
Ωmega
  • 42,614
  • 34
  • 134
  • 203
  • @user1785360 - It does job properly, because of `^` at the begining of `[^...]` – Ωmega Oct 31 '12 at 15:55
  • @user1785360 - I have updated my answer with `quote()` function that should be used in case your `str` contains some special regex characters... – Ωmega Oct 31 '12 at 15:59