Reputation: 840
I have following situation. I have string like this:
something(a,b), something(c,d)
I have to extract from these string characters from parentheses. In this case It will be:
a b c d
I tried to write regex but I failed. I work in Ruby. Thanks for all answers.
Upvotes: 1
Views: 845
Reputation: 70732
No It will be only variations of case from question..
With using your given regular expression, you can use the following to collect all matches in a string into an array. The call to flatten
just makes it easier to process if the regular expression has capture groups, and you are just interested in the list of matches.
string = 'something(a,b), something(c,d)'
matches = string.scan(/\((\w+),(\w+)\)/).flatten
Upvotes: 1
Reputation: 2943
As pointed out by Arup, the following regexp can be used here
re = /\((\w+),(\w+)\)/
Note that this is very basic, and may not catch all of the uses you need. Do you need to be able to account for spaces thrown in there? If so, should they be left out of the matches? Might there be more than two items in some of these parentheticals? You will need to be more specific if this doesn't meet your needs. However, do note that http://rubular.com/ is an amazing resource for messing around with regular expressions.
If you're curious specifically about how to extract the results from this, you can do something like this
string = "this(a,b) that(x,y)"
(string.scan re).flatten
#=> ["a", "b", "x", "y"]
Upvotes: 2
Reputation: 41838
For instance, you can use something like
something\(([^,]*),([^)]*)
and retrieve your strings from Group 1 and Group 2 capture groups.
See demo at http://rubular.com/r/pCh4YbEhZs
subject.scan(/something\(([^,]*),([^)]*)/) {|result|
# If the regex has capturing groups, result is an array with the text matched by each group (but without the overall match)
# If the regex has no capturing groups, result is a string with the overall regex match
}
Upvotes: 1