1

I have the following regex

.{19}_.{3}PDR_.{8}(ABCD|CTNE|PFRE)006[0-9][0-9].{3}_.{6}\.POC

a match is for example

NRM_0157F0680884976_598PDR_T0060000ABCD00619_00_6I1N0T.POC

and would like to negate the (ABCD|CTNE|PFRE)006[0-9][0-9] portion such that

NRM_0157F0680884976_598PDR_T0060000ABCD00719_00_6I1N0T.POC

is a match but

NRM_0157F0680884976_598PDR_T0060000ABCD007192_00_6I1N0T.POC

or

NRM_0157F0680884976_598PDR_T0060000ABCD0061_00_6I1N0T.POC

is not (the negated part must be 9 chars long just like the non negated part for a total length of 58 chars).

user2175783
  • 1,291
  • 1
  • 12
  • 28
  • 2
    _Why_ it seems _dont work_? The first expression [seems to work](https://regex101.com/r/GLTjH3/1) and it is possible just to negate it for case 2: `!str.matches(".*(ABCD006[0-9][0-9]|CTNE006[0-9][0-9]|PFRE006[0-9][0-9]).*")`, or [negate the entire pattern using `matches()`](https://stackoverflow.com/questions/8610743/how-to-negate-any-regular-expression-in-java). [Ideone online demo](https://ideone.com/nJEN8h) – Nowhere Man Oct 06 '21 at 06:38

2 Answers2

4

Consider using the following pattern:

\b(?:ABCD|CTNE|PFRE)006[0-9][0-9]\b

Sample Java code:

String input = "Matching value is ABCD00601 but EFG123 is non matching";
Pattern r = Pattern.compile("\\b(?:ABCD|CTNE|PFRE)006[0-9][0-9]\\b");
Matcher m = r.matcher(input);
while (m.find()) {
    System.out.println("Found a match: " + m.group());
}

This prints:

Found a match: ABCD00601
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • This doesnt seem to work. Here it is my full regex .{19}_.{3}PDR_.{8}\b(?:ABCD|CTNE|PFRE)006[0-9][0-9]\b.{3}_.{6}\.POC. The following string fails but should be a match NRM_0157F0680884976_598PDR_T0060000ABCD00719_00_6I1N0T.POC – user2175783 Oct 06 '21 at 22:21
  • `Here it is my full regex` ... where does my answer ever suggest this regex? – Tim Biegeleisen Oct 06 '21 at 23:18
3

I would like to propose this expression (ABCD|CTNE|PFRE)006\d{1,2}

where \d{1,2} catches any one or two digit number that is it would get any alphanumeric values from ABCD0060~ABCD00699 or CTNE0060~CTNE00699 or PFRE0060~PFRE00699

Edit #1:

as user @Hao Wu mentioned the above regex would also accept if its ABCD0060 which is not ideal so this should do the job by removing 1 from the { } we can get

alphanumeric values from ABCD00600~ABCD00699 or CTNE00600~CTNE00699 or PFRE00600~PFRE00699 so the resulting regex would be

(ABCD|CTNE|PFRE)006\d{2}

  • 1
    But it makes a false positive `ABCD0060`? – Hao Wu Oct 06 '21 at 07:20
  • In the previous regex \d{1,2} would get any digit from 0-99 so I made changes to it such that \d{2} would now get any digit from 00-99,hope this fixes the issue for ABCD0060 – Rakshith B S Oct 06 '21 at 11:51