1

I am trying to use this Re-pattern r'\({2}.+?\){2}' to catch a ((slug1/slug2/slug3 someword)) expression from text.

It gives me the whole expression itself,i.e '((slug1/slug2/slug3 someword))'. Then I parse it using Python:split it to get slug1/slug2/slug3 and someword separately.

How can I get the same using pure Regex pattern with groups. What pattern should be? Any help is appreciated.

Cylian
  • 10,970
  • 4
  • 42
  • 55
Swordfish
  • 181
  • 1
  • 5

2 Answers2

1

Assuming slugs can't contain whitespace:

\({2}(\S*)\s(.*?)\){2}

More explicitly:

\({2}  # two literal '(' characters
(\S*)  # any number of non-whitespace characters, captured in group 1
\s     # any whitespace character
(.*?)  # any number of characters, reluctantly, captured in group 2
\){2}  # two literal ')' characters

So slug1/slug2/slug3 will be in group 1 and someword will be in group 2.

beerbajay
  • 19,652
  • 6
  • 58
  • 75
0

I came up with this regex:

/([\w\/]+) (\w+)/

It evaluates correctly using this command:

perl -e '$a="((slug1/slug2/slug3 someword))"; if ($a =~ /([\w\/]+) (\w+)/) {print "$1 $2"}'
Sicco
  • 6,167
  • 5
  • 45
  • 61
  • Depending on OP's use-case, you might need to add the parens (e.g. if they're running the regex on a file with lots of other text they don't want matched). – beerbajay Jun 07 '12 at 13:28
  • correct :) it would be nice if the author gave us more insight in the structure of the text – Sicco Jun 07 '12 at 13:33
  • text could be anything,it will be used for user input field. – Swordfish Jun 07 '12 at 16:09
  • But will the structure of the text always contain two opening parenthesis and two closing parenthesis? Put it differently, given `((slug1/slug2/slug3 someword))`, which parts will changes? Only `slug1/slug2/slug3 someword`? Or also the `((` and `))`? – Sicco Jun 07 '12 at 16:13
  • ok,got ya. Well, the text will be always with 2 open and 2 closed parenthesis. Only slug1/slug2/slug3 someword will change. – Swordfish Jun 07 '12 at 16:15
  • Good, then beerbajay's and my answer work right? You can accept either of our answers if you think it answers your question and/or upvote answers which you deem helpful. – Sicco Jun 07 '12 at 23:43