I have this regex
(\w+)\s*\:\s*(\W\d+)
set to match something like
"price: $200"
what do I need to do to change it so it will match either "price: $200"
or "$200"
(if the price: part doesn't exist)
I tried
(?:(\w+)\s*\:\s*)*(\W\d+)
but that doesn't work, as it gives me an empty match for the first one
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
They can help you to extract exact information from a bigger match (which can also be named), they let you rematch a previous matched group, and can be used for substitutions.
What is Group in Regex? A group is a part of a regex pattern enclosed in parentheses () metacharacter. We create a group by placing the regex pattern inside the set of parentheses ( and ) . For example, the regular expression (cat) creates a single group containing the letters 'c', 'a', and 't'.
Capturing group. (regex) Parentheses group the regex between them. They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex. (abc){3} matches abcabcabc. First group matches abc.
Non-capturing parentheses group the regex so you can apply regex operators, but do not capture anything. (?:abc){3} matches abcabcabc. No groups. Substituted with the text matched between the 1st through 9th numbered capturing group.
Python Regex Capturing Groups 1 Example to Capture multiple groups. To extract the uppercase word and number from the target string we must first write two regular expression patterns. 2 Regex capture group multiple times. In earlier examples, we used the search method. ... 3 Extract range of groups matches. ...
They capture the text matched by the regex inside them into a numbered group that can be reused with a numbered backreference. They allow you to apply regex operators to the entire grouped regex.
how about:
(\w+\s*:\s*)?(\W\d+)
the ?
means the group will show up 1 or 0 time. you can add your own capture group(s) for convenient data fetching.
(?=.*?:)(\S+)\s*:\s*(\S+)|(\S+)
You can use lookeahead as well.
See demo.
http://regex101.com/r/oO8zI4/5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With