2

I have the following regex defined:

const regEx = new RegExp('[A][A-Z]{2}[0-2]{5}\b', 'g')

I have tested it in online regex testers and they all seem to work. I would like to search through a string for all words that look like this: ADB12210. They have to start with an A followed by 2 upper case letters and end with 5 numbers from 0-2 and be a global search since this could appear multiple times in the string. This seems to work but when I try it by creating a pipe in angular it doesn't find any matches. The match returns null but I am expecting an array like: ['ADB12210', 'ACG12212']. My pipe is as follows:

transform(value: string): any {
  const regExp = new RegExp('[A][A-Z]{2}[0-2]{5}\b', 'g')
  console.log(value.match(regExp)
}

Even if I hard code the check it still returns null:

const string = 'ACG12212'
console.log(string.match(regExp)
5
  • Try this: regExp = /\b[A][A-Z]{2}[0-2]{5}\b/g Commented Nov 12, 2020 at 5:43
  • @anubhava still no match Commented Nov 12, 2020 at 5:46
  • Try using \\b. You may need to backslash the backslash. Commented Nov 12, 2020 at 6:05
  • @FrankYellin that was my problem. Now it works as expected. Create an answer and I will accept it. Commented Nov 12, 2020 at 6:07
  • @Martheli. Thanks. Done. Commented Nov 12, 2020 at 6:08

2 Answers 2

3

You need to use \\b, since so that a single backslash will make through into the string.

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

Comments

1

I removed the last boundary you have because I think your words may or may not have spaces in between and that might be causing it to be null, try with below.

value = 'asdasADB12210asd'
const regExp = new RegExp('[A][A-Z]{2}[0-2]{5}', 'g')
console.log(value.match(regExp))

2 Comments

That works but I don't want it to return on your example value. If there are other characters or numbers around the value then it should not match. So for example, ACG12212 should match but 00000ACG122120000 should not.
You can use negative lookbehind (?<!\d)[A][A-Z]{2}[0-2]{5} and also negative lookahead according to your requirement.

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.