Alex Mazur
Alex Mazur

Reputation: 31

Requires regex to compare last digit in string

Requires regex to compare last digit in string.

// For example: 
const reg = RegExp("anythink...5") // expression to check that the last number is 5
reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc") => true
reg.test("2fae71c8-fc5") => true
reg.test("2364872368745") => true
reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8") => false

Please help me find a solution.

Upvotes: 2

Views: 47

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

You can match 5 optionally followed by any char except a digit or a newline using:

5[^\d\n]*$

You might also use \D* to match any char except a digit, but note that it could also match a newline.

See a regex demo.

const reg = /5[^\d\n]*$/; // expression to check that the last number is 5
console.log(reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc")); // => true
console.log(reg.test("2fae71c8-fc5")); // => true
console.log(reg.test("2364872368745")); // => true
console.log(reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8")); // => false

Upvotes: 0

frontendnils
frontendnils

Reputation: 36

Use regexr.com to construct and check your Regular Expressions. You can even add multiple tests to see if it works for you in a glance.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use

/5(?=\D*$)/
/5(?!\D*\d)/

See the JavaScript demo:

const reg = /5(?=\D*$)/
console.log(reg.test("2fae71c8-a657-41b7-8d8c-3d4da10285fc")) // => true
console.log(reg.test("2fae71c8-fc5")) //=> true
console.log(reg.test("2364872368745")) //=> true
console.log(reg.test("87415B11-7143-4E5B-9B25-6117571DFEC8"))// => false

The 5(?=\D*$) regex matches

  • 5 - a 5 digit char
  • (?=\D*$) - a positive lookahead that requires zero or more non-digit chars till end of string
  • (?!\D*\d) - a negative lookahead that fails the match if there is a digit after 5 and any zero or more non-digit chars.

Upvotes: 1

Related Questions