0

I am trying to figure out how to write the following regex:

assume I can have two types of strings to check and find "value":

string1: CONST1:CONST2:CONST3:value and

string2: CONST1:CONST2:CONST4:value-12345

For string1 this pattern would do

CONST1:CONST2:(CONST3|CONST4):(.*)

where I capture the second group. But I also need to handle the case when "value" is followed by the dash and some other value. I tried it this way:

CONST1:CONST2:(CONST3|CONST4):(.*)(-.*)?

But then second group (.*) will capture everything in string2, including following dash + value2 (12345). Making it (.*?) won't work either, for string1 group2 would return empty String.

Can anyone point me in what direction should I look to find the solution? Should I dig into lookahead and lookbehind or there is a simpler solution?

Thanks in advance.

2 Answers 2

1

Don't use

(.*), but

([^\-]*)

to avoid - in the result.

It is often better to avoid the dot . but give a positive or negative list of allowed characters.

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

Comments

1
^CONST1:CONST2:(CONST3|CONST4):([^\-\W]*)(-[^\W]+)?

Example:

https://regex101.com/r/vL4uG2/2

I tested the regex with the follow text:

CONST1:CONST2:CONST3:hola

CONST1:CONST2:CONST3:hola-43

CONST1:CONST2:CONST4:hola

CONST1:CONST2:CONST4:hola-12345

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.