Home > Back-end >  Regex - Conditional based on first part of text
Regex - Conditional based on first part of text

Time:12-03

Is it possible to make a conditional that does not check part of the string when is not needed?

For example:

Regex: ^[a-zA-Z] .*#[0-9] $

Example text: feature: My name is Oliver #9123

I would like to when the text being:

release: My name is oliver

The same Regex matches both cases not requiring the #9123 for the release prefix, is that possible?

I have tried to use some regex conditionals that I found on google, but didn't have success.

CodePudding user response:

What you want is an optional group:

^[a-zA-Z\s] (#[0-9] )?$

So that, the following strings will match:

"My name is Oliver #9123"
"My name is Oliver"

And this won't:

"This is not valid #xxx"

Regex playground

CodePudding user response:

You could try a logical OR (|) in the regexp:

const tests=["My name is Oliver #9123",
             "release: My name is oliver",
             "this should fail",
             "#12345 another fail"];

tests.forEach(str=>
  console.log(str " - " (str.match(/^release|[a-zA-Z] .*#[0-9] /)?"pass":"fail"))
)

CodePudding user response:

If I understood you, you want the regex to work on part of the whole string, then you can create a function that splits the string into two parts - the part that will be checked by the regex and the part that won't be checked - then you can pass the part of the string to regex.

  • Related