user597118
user597118

Reputation: 91

Regex to match address and optional suffix

I have addresses in two formats:

SomeHouse,
Holbrook,
Belper,
Derbyshire,
DE56 0RR

and

SomeHouse,
Holbrook,
Belper,
Derbyshire,
DE56 0RR(123123123123)

The number only ever appears right at the end, is always in brackets and always 12 digits.

I am trying to get a regex to match two groups ... the address and the number (if it is there).

It is a head banger (for my inregexperienced self) since i cant get my expression to work on both types of address.

I have

(?<address>.*)(?<bracketsandnum>\((?<num>[0-9]{12})\))$

which also uses a group to match the brackets - not so sure i need that bit :) certainly not as a named group anyway.

Please advise!

Cheers, James.


Update

I have used the answer provided by Martinho, Qtax. Many thanks to them. Now i understand a bit more, i see my question is similar to the following:

Ignoring an optional suffix with a greedy regex

Upvotes: 2

Views: 1982

Answers (1)

Qtax
Qtax

Reputation: 33908

Make the second group optional with ?, and use a non-greedy match in the first group (by modifying * with ?). Something like this:

^(?<address>.*?)(?:\((?<num>\d{12})\))?$

Upvotes: 4

Related Questions