Reputation: 4149
I am trying to write a regular expressions that will match multiple sub-strings in a given string. Here is my requirement:
Input String: value(abc) or v(def) or s(xyz)
My regular expression should match both value(
and v(
.
This is what I wrote: ^(?:value\(|v\()
But the above regex matches either value(
or v(
, not both. I need the regex to match both. Is there any way to do this?
Also, Is there any possible way in which I can get the substring between the brackets? Like a way to pick abc or def in the above example?
Upvotes: 1
Views: 506
Reputation: 8037
Your regex starts off with a start-of-string anchor (^
). This causes the regex to only match at the start of your string. Since "v(def"
is not at the start of the input string "value(abc) or v(def) or s(xyz)"
, the regex will not match it. Removing the start-of-string anchor will fix this.
In addition, the two alternatives in your regex are mostly the same, aside from some additional characters in the first alternative. Your regex could be simplified to the following:
v(?:alue)?\(
Update: To get the value of the expression inside of the parenthesis, you can use a capturing group (surround an expression with ()
). Capturing groups are numbered based on the position of their opening parenthesis. The group whose (
comes first is group "1", the second (
is group "2", and so on. Depending on what regex engine you are using, you might also be able to use named capturing groups (?<name>
...)
(I know .NET supports them). You would then use your engine's method of retrieving the value of a capturing group.
For example, the following regex will match:
v
or value
(
)
The optional value will be stored in the "value" capturing group. You will want to change the expression inside the value group to match the format of your values.
v(?:alue)?\((?<value>[a-zA-Z]*)\)
(Visualizations created using Debuggex)
Upvotes: 2
Reputation: 5664
To match the contents of the string between parentheses in your string, capture it with a parenthesized subexpression:
(?:value\(|v\()([^)]*)\)
This pattern matches:
(?:value\(|v\()
- the opening value(
or v(
.([^)]*)
- any number of characters that aren't )
. Putting this part in parentheses means that whatever was matched will be saved in a match group.\)
- the final close parenthesisThe way to actually retrieve the value depends on the language you're using; typically, the regular expression search function returns some sort of match object, which will provide a method to give you the value in parenthesis. For example, in python:
import re
str = 'value(abc) or v(def) or s(xyz)'
match = re.search(r'(?:value\(|v\()([^)]*)\)', str)
if match:
print match.group(1)
will print abc
.
Upvotes: 0