Wokoman
Wokoman

Reputation: 1119

how can I ignore nested patterns with regex

Not sure if the title is the best way to describe the problem, but what I need to achieve is the following :

I have a list of strings that follow a fairly simple pattern, so string values optionally followed by a note/remark, using brackets. Aim is to isolate the bracketed part, which works fine as long as there are no other brackets within the bracket part

For example :

This is some string (with comment)

Can be split as follows (very lazy)

regex.Pattern = "^(.*)(\(.*\))$"

and it provides me output as follows and as expected.

part 1 : This is some string
part 2 : (with comment)

The problem is that sometimes I can have strings as follows

This is some string (with comment (and even more comment))

And I'm failing to get the correct output. What I need to acchieve is the following :

part 1 : This is some string
part 2 : (with comment (and even more comment))

So how can I achieve this ?

Upvotes: 0

Views: 75

Answers (3)

Sivasakthi Jayaraman
Sivasakthi Jayaraman

Reputation: 4724

Another simple solution:

^(.*?)(\(.+)$  

Demo:
http://regex101.com/r/vQ9xM4/1

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

You need to make the .* to do a non-greedy match by adding a reluctant quantifier ? next to the *

^(.*?)(\(.*\))$

DEMO

OR

^([^(]*)(\(.*\))$

Upvotes: 1

Kamehameha
Kamehameha

Reputation: 5473

This should work -

^([^(]*)(\(.*\))$

Demo here

Upvotes: 1

Related Questions