2

I have a string (VIN) like this:

String vin = "XTC53229R71133923";

I can use OR to see if there are characters Q,O,I:

String regExp = ".*[QOI].*";

This works.

However I can not check that any of these 3 letter are NOT in the string.

It means: (NOT Q) AND (NOT O) AND (NOT I). I tried negative lookahead:

String regExp = "(?!.*[QOI].*)";

This doens't work. In "XTC5Q3229R71133923" it returns true.

The main issue - I have 2 conditions:

  1. Number of characters (A-Z0-9) in the string should be 17.
  2. The string should not have Q,O,I.

I can check this with 2 regexps:

  1. String regExp = "^([A-Z0-9]{17})$"; //should be true
  2. String regExp = ".*[QOI].*"; //should be false

But is there a way to combine these 2 checks in one regular expression?

Kirill Ch
  • 5,496
  • 4
  • 44
  • 65

2 Answers2

3

How about just using a custom range that doesn't include the characters you do not want?

String regexp = "^([A-HJ-NPR-Z0-9]{17})$";
Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30
  • However I really would like to get how to combine AND and NOT for some more diffucult issues if this is possible... – Kirill Ch May 29 '18 at 14:57
  • 1
    Custom ranges are almost always better even for more complex cases, as they're rather simple to understand, compared, say, to negative look-aheads. See this related question for example: https://stackoverflow.com/questions/7548787/regex-for-and-not-operation - yes, it seem possible, but, as per Zawinski's effect, you'll just end up with two problems instead of one , the other being your regular expression :) – Alex Savitsky May 29 '18 at 15:03
  • Ok. It seems the best answer. It really converts my 2 RegExps in one. I'm curious still is there an elegant way to combine AND and NOT. However this really solves my issue. Thank you. – Kirill Ch May 29 '18 at 15:13
  • 1
    Please change "O" to "N" as I can't change only 1 character. In my question "O" should be excluded. – Kirill Ch May 29 '18 at 15:17
  • 1
    Good catch, my bad. Fixed – Alex Savitsky May 29 '18 at 15:18
3

Here you go ^[^QOI]{17}$. Starting a charcter class with ^ means "do not match any of these characters".

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • 1
    This would also include the whole Unicode table as the allowed character set. I believe the question was how to exclude certain characters **while** keeping the `A-Z0-9` range – Alex Savitsky May 29 '18 at 14:52
  • This might be not exact answer however it might be useful in some other cases. – Kirill Ch May 30 '18 at 19:12