Eugenio Rogriguez
Eugenio Rogriguez

Reputation: 9

Javascript Regex for matching string between strings and a specific length

How should I write regex to extract a substring from a string with the following conditions:

Meaning A + 12345678 + 00

eg: Input: ABC12345678CRP1234567F2801209A1234567800<<<33

Output: 12345678

So far, I have tried below regex, but seems like I am missing something?

/(A(.*)00)/ (this fails because it doesnt match with the correct length

/(A(.*)00){7,8}/ (im not sure why this fails, but the idea was to keep the same as before and add the length restriction)

Any ideas?

Upvotes: 0

Views: 697

Answers (3)

user7571182
user7571182

Reputation:

You may try:

A\d{7,8}00

Explanation of the above regex:

  • A - Matches A literally.
  • \d{7,8} - Matches digit 7 to 8 times.
  • 00 - Matches 00 literally.

You can find the demo of the above regex in here.

let string = `ABC12345678CRP1234567F2801209A1234567800<<<33`;
const regex = /A(\d{7,8})00/gm;

console.log(regex.exec(string)[1]);

Upvotes: 1

Vishal Singh
Vishal Singh

Reputation: 6234

(?<=A)(\d{7,8})(?=00)

(?<=A) Positive lookbehind will make sure the matching string contains A
(?=00) Positive lookahead will make sure the string is followed by 00

https://regex101.com/r/nP0Qu0/1

Upvotes: 0

adelriosantiago
adelriosantiago

Reputation: 8124

You are looking for this regex: /(A(\d{8})00|(A(\d{7})00))/gm

Explanation:

  • A(\d{8})00: Starts with "A" and has 8 digits and ends with "00", or
  • |: Or
  • (A(\d{7})00): Starts with "A" and has 7 digits and ends with "00", or

You will get the full match ("A########00" or "A#########00")in the second group and only the number ("########" or "#########") in the second group.

Demo: https://regex101.com/r/Ml1xih/1/

Upvotes: 0

Related Questions