Home > database >  Regex to match words ending with the letter a followed by how many a's there were at the end of
Regex to match words ending with the letter a followed by how many a's there were at the end of

Time:01-09

We only ever want to match words ending with one or two a's. So we wouldnt match aaa3. We also don't want to match words where the number doesn't match e.g. hea2

Here are some example strings that would have matches:

Iaa2 ama1 from the uka1, Iaa2 like the uka1 very much

Dog isa1 aaa2 pet animal

The matches I am looking for:

Iaa2 ama1 uka1 Iaa2 uka1

isa1 aaa2

Thanks!

CodePudding user response:

\b matches a word boundary. \w matches any word character (letters, digits, underscores). Since your words can only end with "a1" or "aa2", an alternation would achieve the goal:

/\b\w*(?:a1|aa2)\b/g

e.g.

input.match(/\b\w*(?:a1|aa2)\b/g)

CodePudding user response:

Apparently you don't want to disallow aaa2, as it would also match aaa3. Here is a solution that matches words that end in letters a followed by a number that indicates the number of letters a found. I added also aaa3, you could add more if needed.

const input = `Iaa2 ama1 from the uka1, Iaa2 like the uka1 very much
Dog isa1 aaa2 pet animal`;
const matches = input.match(/\w (?:a1|aa2|aaa3)\b/g);
console.log(matches)

Output:

  "Iaa2",
  "ama1",
  "uka1",
  "Iaa2",
  "uka1",
  "isa1",
  "aaa2"
]

Explanation of regex:

  • \w -- 1 word chars
  • (?: -- non-capture group start (for logical or)
    • a1 -- literal a1
  • | -- or
    • aa2 -- literal aa2
  • | -- or
    • aaa3 -- literal aaa3 (rinse and repeat if needed)
  • ) -- non-capture group end
  • \b -- word boundary
  • add g flag to match multiple times
  • Related