Home > Blockchain >  Grouping character strings
Grouping character strings

Time:07-30

I have 3 text :

  • Simple test 1 [https://www.test.com/aaa/bbb#rrr] [1.111111, 0.222222]
  • Simple test 2 [https://www.test.com/aaa/bbb#rrr]
  • Simple test 3

I'm looking to get this :

    0 => Simple test 1
    1 => [https://www.test.com/aaa/bbb#rrr]
    2 => [1.111111, 0.222222]
    
    0 => Simple test 2
    1 => [https://www.test.com/aaa/bbb#rrr]
    
    0 => Simple test 3

With this it's ok for the first :

    (.*?) \[(.*?)\] \[(.*?)\]

For the other two it does not work.

Any idea ? Thank for your help.

CodePudding user response:

If you want to match the square brackets, you have to put them inside the capture group.

You can make the last 2 capture groups optional inside a non capture group, where you would also make the leading space part of the optional group.

Instead of a non greedy dot, you can use a negated character class and wrap the pattern between anchors.

Regex demo

^([^][] )(?: (\[[^][]*\])(?: (\[[^][\n]*\]))?)?$
  • Related