Ignasi
Ignasi

Reputation: 631

Regex match different numbers when only this number is present

Good morning,

I have been having issues with regex in finding the way to implement such this case:


Input string (tested string) can be any of those options:


My regex search would always try to match a known string which will always be as follows:


I have already tried it but without success: https://regex101.com/r/0ojdb9/3


To sum up, when I have the known string to build the regex (let's say "12345") when I test it the match should only occur:

Upvotes: 1

Views: 1556

Answers (2)

Ignasi
Ignasi

Reputation: 631

I am answering my question but all credit goes to the user Egan Wolf, since he was the one posting the solution in the comments of the original post (I don't know how to tag him or give the credit to him)

The answer to my question was solved with this regex:

([^0-9;\n]*(?<!\d)1234567890(?!\d)[^0-9;\n]*)

And can be checked here: https://regex101.com/r/0ojdb9/4

Thank you very much for your help!

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626871

You may use

/(?:^|\D)12345(?!\d)/

It matches:

  • (?:^|\D) - start of string or any non-digit char
  • 12345 - the known value
  • (?!\d) - there must be no digit right after the known value.

See JS demo:

val = 12345;
rx = new RegExp("(^|\\D)" + val + "(?!\\d)");
console.log(rx.test("12345"));  // Match
console.log(rx.test("123456")); //  NO Match
console.log(rx.test("012345")); //  NO Match
console.log(rx.test("12345;"));  // Match
console.log(rx.test("123456;")); //  NO Match
console.log(rx.test("012345;")); //  NO Match
console.log(rx.test("a12345"));  // Match
console.log(rx.test("a123456")); //  NO Match
console.log(rx.test("a012345")); //  NO Match
console.log(rx.test("a12345;"));  // Match
console.log(rx.test("a123456;")); //  NO Match
console.log(rx.test("a012345;")); //  NO Match

Upvotes: 1

Related Questions