-1

Is there any way to add a regex exception to a regular expression?

Example:

(regular expression/regular expression to ignore)

I have the following regular expression:

\W

But would like for it to ignore strings inside quotation marks (Regex i will use for this is: "(.*?)"). But i don't know how to add an exception to the \W regex.

I want something like this:

\W(ignore->"(.*?)")

Any ideas? Any help will be appreciated.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Carlos Daniel
  • 449
  • 4
  • 14

2 Answers2

0

Edit: Your question asks about \W (non-word characters), but perhaps you meant to split on those. It seems you meant to match those, so I changed the upper-case \W to lower case \w in my answer.

You might be looking for something like this: (?:"[^"]*?"|\w)+

The idea is to treat quoted substrings differently. Here is how it works:

  • One or more of the contents: (?: "[^"]*?"|\w )+ where the contents are...
  • Either a quoted string [^"]*?" or word character \w
  • The quoted string is [^"]*?" is a " followed by as few as possible non-quote characters [^"]*?, followed by the closing ".
Dharman
  • 30,962
  • 25
  • 85
  • 135
agent-j
  • 27,335
  • 5
  • 52
  • 79
  • 1
    This `(?:"[^"]*?"|\w)+` is not going to help in the end, since a mere `String str = "with \"quotes\" inside";` line will break it. – Wiktor Stribiżew Feb 12 '21 at 20:27
  • Yes, this example only works for simple strings. If your source file includes things like `$"{("h")}"` or `@">""<"` it would likely need a language parser instead of regex. – agent-j Feb 15 '21 at 18:54
0

I don't know how to do this using a single regex, but you can do it in 2 steps. (i) Replace the exception with an empty string; (ii) Search in the new string.

let text = `Hey "aaa bbbb &&&&&&" !@# "hahaha 123 %%%" !!!`;

let newText = text.replace(/"(.*?)"/g,"");

console.log(newText);

let matches = newText.match(/\W/g);

console.log(matches);
Andre Marasca
  • 270
  • 1
  • 6