Matt
Matt

Reputation: 27011

How can I capture the contents of one or more strings using a regex?

Let's say I have the following three strings:

(section1){stuff could be any character, i want to grab it all}

(section1)(section2){stuff could be any character, i want to grab it all}

(section1)(section2)(section3){stuff could be any character, i want to grab it all}

So if applied regex to my expressions, for the first I would get:

section1

stuff could be any character, i want to grab it all

if applied regex to my expressions, for the second I would get:

section1

section2

stuff could be any character, i want to grab it all

and if applied regex to my expressions, for the third I would get:

section1

section2

section3

stuff could be any character, i want to grab it all

I have the following regex:

((?<section>.+))+{?<term>.+}

So look for inside parens and repeat and then what's inside the curly brackets. It doesn't seem to work Any clue? This has always been my Achille's heel.

Upvotes: 0

Views: 113

Answers (3)

Scott Baker
Scott Baker

Reputation: 10453

(?<section>\(.+?\))+?(?<term>\{.+\})

is probably closer to what you're looking for.

This will match however many (sectionN) segments you have, along with the {term}

Upvotes: 2

akf
akf

Reputation: 39515

one thing to keep in mind as well when writing your regex, the occurance braces {} contain numbers, not wild cards.

 <regex>{3}  //will match three exactly
 <regex>{0,3} // will match up to and including three
 <regex>{3,} // will match three or more

it is also nice to have a utility to test your strings out while trying to compose your pattern. here is one such online tool

Upvotes: 0

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340496

I didn't understand what you wanted very well, but I'll try to answer anyway

(\(section1\)(\(section2\)(\(section3\))?)?)(.*)

That will match (and capture) (section1) followed by something else (or nothing) and optionally followed by a (section2) that could, in turn, be optionally followed by (section3)

I'm almost certain this isn't what you need, but at least will prompt you to describe your question better :-)

Upvotes: 0

Related Questions