Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a capture group that doesnt always exist?

Tags:

python

regex

I have a regex something like

(\d\d\d)(\d\d\d)(\.\d\d){0,1}

when it matches I can easily get first two groups, but how do I check if third occurred 0 or 1 times.

Also another minor question: in the (\.\d\d) I only care about \d\d part, any other way to tell regex that \.\d\d needs to appear 0 or 1 times, but that I want to capture only \d\d part ?

This was based on a problem of parsing a

hhmmss

string that has optional decimal part for seconds( so it becomes

hhmmss.ss

)... I put \d\d\d in the question so it is clear about what \d\d Im talking about.

like image 717
NoSenseEtAl Avatar asked May 13 '13 12:05

NoSenseEtAl


People also ask

How do you write a non-capturing group in regex?

Sometimes, you may want to create a group but don't want to capture it in the groups of the match. To do that, you can use a non-capturing group with the following syntax: (?:X)

Why use a non-capturing group?

A non-capturing group lets us use the grouping inside a regular expression without changing the numbers assigned to the back references (explained in the next section). This can be very useful in building large and complex regular expressions.

What does a non-capturing group mean?

Overview. Non-capturing groups are important constructs within Java Regular Expressions. They create a sub-pattern that functions as a single unit but does not save the matched character sequence. In this tutorial, we'll explore how to use non-capturing groups in Java Regular Expressions.

How do capture groups work regex?

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


1 Answers

import re

value = "123456.33"

regex = re.search("^(\d\d\d)(\d\d\d)(?:\.(\d\d)){0,1}$", value)

if regex:
    print regex.group(1)
    print regex.group(2)
    if regex.group(3) is not None:
        print regex.group(3)
    else:
        print "3rd group not found"
else:
    print "value don't match regex"
like image 96
stalk Avatar answered Sep 22 '22 19:09

stalk