A regular expression for matching two numbers that are not equal

I was wondering how I can match two numbers, but which do not match. So it would be nice to match 12, but not 11.

What I have so far: I need to match strings like "P12", and I did this with this regular expression:

^P([1-6]{1})([1-6]{1})$ 

But now my problem is how to match only strings like P12 or P32 where numbers are not repeated.

Any help or guidance for reading materials would be greatly appreciated.

edit: Thanks to everyone for your answers, but I tested this on RAD (radsoftware.com.au/regexdesigner). I know, I should have mentioned this: /, and most of them do not work there. I saw a solution sent from one user, but this is no longer visible, I don’t know why he deleted it? anyway: this is what worked:

 ^P([1-6]{1})(?!\1)([1-6]{1})$ 

Thanks everyone!

+3
source share
5 answers

Use this:

 ^P((1[2-6])|(2[13-6])|(3[124-6])|(4[1-356])|(5[1-46])|(6[1-5]))$ 
+4
source

You need to use backreferences . Essentially, you need to first combine the first digit ( [1-6] ), keep this correspondence (using a pair of parentheses), and then use this link to match anything but it ( [^\1] ), letters ( A-Za-z ), and 0, 7, 8, and 9:

 P([1-6])[^\1A-Za-z0789] 
+3
source

try it

 ^P([1-6])([^\\1\D07-9])$ 

Tested on js shell

 /^P([1-6])([^\\1\D07-9])$/.test("P12") true /^P([1-6])([^\\1\D07-9])$/.test("P11") false 

Other test cases

 /^P([1-6])([^\\1\D07-9])$/.test("P10") false /^P([1-6])([^\\1\D07-9])$/.test("P1b") false /^P([1-6])([^\\1\D07-9])$/.test("P17") false 
+2
source

JG is right, you want to use backlinks for this problem. Since we already have the correct answer, I just wanted to make one comment about the current regular expression:

^P([1-6]{1})([1-6]{1})$

{m,n} means matching with the previous item at least m and no more than n times. And {n} means coinciding with the previous thing exactly n times. Therefore, when you put [1-6]{1} , you say: "Align one digit in the range 1-6 exactly once." It is redundant, you can just say [1-6] on its own. so your regex can be simplified:

^P([1-6])([1-6])$

this, of course, does not take into account the problem with invalid duplication of numbers, but others have already solved this problem.

+2
source

I think you need to learn how to reverse cue. This allows you to see if the previously mapped group matches the corresponding group. You can get more information about this here.

+1
source

Source: https://habr.com/ru/post/1343159/


All Articles