Regex to match address and optional suffix

空扰寡人 提交于 2021-02-01 05:11:13

问题


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


回答1:


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})\))?$


来源:https://stackoverflow.com/questions/6663258/regex-to-match-address-and-optional-suffix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!