0

I have a regular expression pattern: [a-zA-Z0-9]{8}.

Is there some way to negate this pattern? I mean that using that expression I should be able to match all substrings that do not match this pattern.

I tried a negative look behind - (?!(a-zA-Z0-9{8})), but that has never worked in JavaScript.

4
  • You can use it in a .split(). Check jsfiddle.net/hwpaqmn9 Commented Jan 7, 2016 at 12:19
  • Do you want to match a string, or do you want to test a string? Commented Jan 7, 2016 at 12:29
  • Yes, that works fine. I will try it in our company framework. I must implement that JSON there, but it may work. Thanks. Commented Jan 7, 2016 at 12:31
  • Ah, so I can post it. Commented Jan 7, 2016 at 12:32

1 Answer 1

3

In order to obtain all the substrings that do not match a specific pattern, you can use String#split:

var re = /[a-zA-Z0-9]{8}/;
var s = "09 ,Septemeber";
document.body.innerHTML += JSON.stringify(s.split(re).filter(Boolean));

The idea is that those substrings that match will be delimiters, and will be missing from the obtained array.

I added .filter(Boolean) to get rid of empty array elements that often appear when splitting with a regex.

Note that the pattern should not contain capturing groups, or the captured substrings will be part of the resulting array.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the (?!(a-zA-Z0-9{8})) regex pattern does not match any text, only locations (empty strings) that are not followed by a followed by -, followed by z.... and followed by 8 occurrences of the 9 digt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.