Need Help on RegEx

Hi,

I have a text containing magic tokens like

This is an @@@CHECKVALUE_MIN_FROM_TOLERANCE_2_1@@@ text text to show my 
problem with @@@CHECKVALUE_MIN_FROM_TOLERANCE_12_1@@@ token.

Now I need a Regex which will return all these magic token in the text.

CHECKVALUE_M.._FROM_TOLERANCE_._. or
CHECKVALUE_M.._FROM_TOLERANCE_[0-9]_.

works for all tokens with numbers not longer then 1 digit. So the first token will be found.

What is the solution to get both token?

Just found it

CHECKVALUE_M.._FROM_TOLERANCE_\d+_.

As long as the second value cant be a 10+, sure.

It probably is better to use . only when necessary, but it works.

Why M..? If it can match MIN and MAX I would use (MIN|MAX) to avoid it matching random crap that happens to be three chars long and starts with an M.

Also, I would replace the last dot with \d to make it only match numbers (or indeed as @m_hutley pointed out d+ if numbers above 9 are possible).

Sorry for the daft question, but is the capture specifically CHECKVALUE_MIN_FROM_TOLERANCE_2_1... or is it anything between @@@?

e.g. /@@@(?<token>.+?)@@@/g

const text = `
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quas 
repellendus doloremque @@@CHECKVALUE_MIN_FROM_TOLERANCE_2_1@@@ 
velit corporis, @@@CHECKVALUE_MIN_FROM_TOLERANCE_12_1@@@ 
quidem dolorem dicta ab necessitatibus animi labore veritatis 
iure voluptates asperiores cumque.
`

const tokensRx = /@@@(?<token>.+?)@@@/g

// matchAll returns an iterator
for (const match of text.matchAll(tokensRx)) {
  console.log(match.groups.token)
}
// "CHECKVALUE_MIN_FROM_TOLERANCE_2_1"
// "CHECKVALUE_MIN_FROM_TOLERANCE_12_1"

// accessing capture group at index 1
console.log(
  Array.from(text.matchAll(tokensRx), (match) => match[1])
)
// ["CHECKVALUE_MIN_FROM_TOLERANCE_2_1","CHECKVALUE_MIN_FROM_TOLERANCE_12_1"]

// accessing capture group by name
console.log(
  Array.from(
    text.matchAll(tokensRx), 
    (match) => match.groups.token
  )
)
// ["CHECKVALUE_MIN_FROM_TOLERANCE_2_1","CHECKVALUE_MIN_FROM_TOLERANCE_12_1"]

Its special on the tokens with TOLERANCE_MIN or TOLERANCE_MAX and then two numbers separated by an underscore where the second number can only be 1 or 2.

1 Like

Had a feeling that might be the case. I’m sure you wouldn’t have asked otherwise :slight_smile:

/@@@(?<token>CHECKVALUE_M(?:IN|AX)_FROM_TOLERANCE_\d+_[12])@@@/g