0

In JS, I have some strings which need to break down into capture groups. The problem is there are some variations.

String variations:

              group3::group4
       group2:group3::group4
       group1|group3::group4
group1|group2:group3::group4

So far I've able to build the below regex pattern. Which captures when all groups are there. But I wasn't able to capture each group when one or more groups are missing. Can anyone help me with this to figure it out? (Every time each group must be captured by the relevant capture group)

\([^\r\n]+)?\|([^\r\n]+)?:([^\r\n]+)?::([^\r\n]+)?\g

This runs for each string in a loop. So the final result should looks like this for each string.

array(01 => "group1", 02 => null, 03 => "group3", 04 => "group4")

Thanks in advance.

--[ANSWER]--

With the help of @tshiono, I coded the following example, Posting here in case if anyone needed it.

// const text = 'group3::group4';
// const text = 'group2:group3::group4';
// const text = 'group1|group3::group4';
const text = 'group1|group2:group3::group4';

const regex = /(?:([^:|\s]*)\|)?(?:([^:|\s]*):)?([^:|\s]*)::([^:|\s]*)/;
const match = text.match(regex);

console.log( match );
6
  • Can you show us what the desired result would be please, also the code you wrote would help in producing a good answer, is it JS or PHP Commented May 21, 2021 at 10:13
  • Each text (for example text "group4" must go to the capture group 4). This is run by a loop (array) so one line at a time. Commented May 21, 2021 at 10:19
  • So the final result should looks like this array(01 => "group1", 02 => null, 03 => "group3", 04 => "group4"). Commented May 21, 2021 at 10:23
  • If you put that into the QUESTION, then people can see it Commented May 21, 2021 at 10:23
  • 1
    @stackminu Would this help? Commented May 21, 2021 at 10:26

1 Answer 1

3

Would you please try the following:

/(?:([^:|\s]*)\|)?(?:([^:|\s]*):)?([^:|\s]*)::([^:|\s]*)/gm

Demo

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

1 Comment

Hey, Really appreciate your help on the above pattern. Anyway, my requirement got a little bit advanced, and now I'm clueless about how to match, I'm pretty sure you can help me with this as well. Will you be able to take a look: regex101.com/r/yL7gZ9/1

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.