0

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

  • Starting character should be A
  • Last 2 characters should be 00.
  • Total length of string should be between 7 to 8
  • Only numbers

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?

2
  • 1
    Probably, A(\d+)00 is enough. Commented Jul 6, 2020 at 18:38
  • I believe you mean, "The string must be preceded by 'A' and followed by '00'". As stated 'A' and '00' are part of the string that contains 7-8 characters. Commented Jul 6, 2020 at 21:11

3 Answers 3

1

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]);

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0
(?<=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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.