0

I have a string:

"whatever( here i com  ( asdfasDF ( ) ) ) go home"

I want to extract everything between the first "(" and last ")" which is:

" here i com  ( asdfasDF ( ) ) "

What is a good regular expression to extract that?


Update:

If my string contains newline chars the following works:

/\((([.|\s|\S])*)\)/
3
  • 5
    have you tried running through some basic regex tutorials? Commented Apr 28, 2013 at 13:27
  • 2
    rubular.com is great for testing out regexes. Commented Apr 28, 2013 at 13:39
  • "Your string"? Whose string? Didn't you write "Lets say I have a string"? Commented Apr 28, 2013 at 14:38

3 Answers 3

4

A greedy expression with a capture, e.g.:

/\((.*)\)/
Sign up to request clarification or add additional context in comments.

1 Comment

this breaks when I have new line characters in my string
3
"whatever( here i com  ( asdfasDF ( ) ) ) go home"[/\((.*)\)/m, 1]

or

"whatever( here i com  ( asdfasDF ( ) ) ) go home"[/(?<=\().*(?=\))/m]

Comments

2
str = "whatever( here i com ( asdfasDF ( ) ) ) go home"
p str[str.index("(")+1..str.rindex(")")-1]

3 Comments

could you do str[str.index("(")+1...str.rindex(")")-1]?
@JanDvorak Excellent post tips :) done according to you... like it :)
Actually, I mixed up ... (right-exclusive) and .. (inclusive). I meant the latter. I've just tested (I hoped you would)

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.