匹配可能存在或可能不存在的组 [英] Matching a group that may or may not exist

查看:113
本文介绍了匹配可能存在或可能不存在的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的正则表达式需要解析一个看起来像这样的地址:

My regex needs to parse an address which looks like this:

BLOOKKOKATU 20 A 773 00810 HELSINKI SUOMI
-------------------- ----- -------- -----
          1            2       3      4*

第一,第二和第三组将始终存在于一个地址中.组4可能不存在.我写了一个正则表达式,可以帮助我获得第一,第二和第三部分,但我也需要第四部分.第4部分是国家/地区名称,可以是FINLANDSUOMI.如果地址中不存在第四部分,则第四组将为空.到目前为止,这是我的正则表达式,但第三组也捕获了该国家.有帮助吗?

Groups one, two and three will always exist in an address. Group 4 may not exist. I've written a regex that helps me get the first, second and third part but I would also need the fourth part. Part 4 is the country name and can either be FINLAND or SUOMI. If the fourth part didn't exist in an address the fourth group would be empty. This is my regex so far but the third group captures the country too. Any help?

(.*?)\s(\d{5})\s(.*)$

(我将使用Oracle的REGEXP函数)

(I'm going to be using this Oracles REGEXP function)

推荐答案

将正则表达式更改为:

(.*?)\s(\d{5})\s(.+?)\s?(FINLAND|SUOMI)?$

让第三个组没有贪心会让您匹配可选的空格+国家(地区)选择.如果第4组不匹配,我认为它将是未初始化的,而不是空白,这取决于语言.

Making group three none greedy will let you match the optional space + country choices. If group 4 doesn't match I think it will be uninitialized rather than blank, that depends on language.

这篇关于匹配可能存在或可能不存在的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆