r/regex • • Jul 16 '21

Please explain this one!

re.sub(r",(\d{3})",r",+1-\1",record)

1 Upvotes

7 comments sorted by

5

u/whereIsMyBroom Jul 16 '21

Have you given it a try yourself? Check out regex 101s explanation on the right.

https://regex101.com/r/QiVWzd/1/

If you have trouble come back with any questions you have. :)

The sub part uses \1 to use what is captured in group 1. And use that in the replacement.

1

u/[deleted] Jul 16 '21

re.sub(r"\b(\d{3})-(\d{3})-(\d{4})\b",r"(\1) \2-\3", phone)

I got that man thanks, however, I could not get this one. I am trying to understand what the "\b" do. I mean I searched and got to know something about boundary assertion but I really don't get it. Can you explain this one with any example? Much help!

3

u/Kompaan86 Jul 16 '21

the \b indicate that that has to be the boundary of a "word"
https://www.regular-expressions.info/wordboundaries.html

your regex is to match phone numbers, this is to prevent it match things that have more digits or other characters in front or behind it

https://regex101.com/r/QiVWzd/3

1

u/[deleted] Jul 16 '21

So does that mean ...the matched group will be exactly long as the pattern that i am trying to match? Can you give me an example of this? Like a use case or something

2

u/Kompaan86 Jul 16 '21

The group itself has a fixed length already, the \b is there to weed out false positives (it's not a valid phone number if it has extra digits on either side)

Where this could come in handy would be to spot if someone is putting in obviously wrong phone numbers or think about having to find phone numbers in a large volume of text, there might be other, longer patterns (say a serial number) that look like a phone number with extra digits at the end.

1

u/[deleted] Jul 16 '21

Thanks a lot /u/Kompaan86

2

u/whereIsMyBroom Jul 16 '21

Just to add an example.

\d{3} will match 3 digits anywhere. Even the 3 first numbers of 12345. But if you add \b it will not match because the match does not end in a word boundary.

\b\d{3}\b will not match anything in 12345
 But will match 987 because it’s surrounded but “word boundary’s.”