简体   繁体   中英

Regex how to extract words from parentheses

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.

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"]

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM