简体   繁体   English

正则表达式可选匹配,没有贪婪

[英]Regular Expression optional matches without greediness

For educational purposes, I'm trying to match name, phone and email of the following content: 出于教育目的,我正在尝试匹配以下内容的姓名,电话和电子邮件:

John
+1 288298600
john@site.com

Billy

Mike
+1 768397651
mike@site.com

Patrick
+2 938468172

Jack
jack@site.com

I know how to get all emails and all phones from that, but what I want to do here is different. 我知道如何从中获取所有电子邮件和所有手机,但我想在这里做的是不同的。

I want to get, for each name (John, Billy, Mike, Patrick, Jack) their phone (if any) and their email (if any). 我希望得到,每个名字(约翰,比利,迈克,帕特里克,杰克)他们的电话(如果有的话)和他们的电子邮件(如果有的话)。 So matches would be like 所以比赛就像

'John',    '+1 288298600',  'john@site.com'
'Billy',   '',             ''
'Mike',    '+1 768397651', 'mike@site.com'
'Patrick', '+2 93868172',  ''
'Jack',    '',             'jack@site.com'

Notice that if there is no corresponding info (phone or email) it matches an empty string. 请注意,如果没有相应的信息(电话或电子邮件),则它与空字符串匹配。 How can I do that? 我怎样才能做到这一点?

My attempt: ([A-Za-z0-9]+)(?:.*?(\\+.*?)|.*?)(?:.*?(.*?\\@site.com)|.*?) 我的尝试: ([A-Za-z0-9]+)(?:.*?(\\+.*?)|.*?)(?:.*?(.*?\\@site.com)|.*?)

Anyone can guide me in the right direction? 任何人都可以指导我朝着正确的方向前进

Don't try to do this using multiple matches, it won't lead you anywhere. 不要尝试使用多个匹配来执行此操作,它不会引导您到任何地方。 Instead, match one time per entry, and use capturing groups to extract relevant data. 相反,每个条目匹配一次,并使用捕获组来提取相关数据。

Here's an example (with the mx flags): 这是一个例子(带有mx标志):

^(?<name>[\p{L}\h]+$)\R
(?:(?<phone>^\+[\d\h]+$)\R)?
(?<mail>^.+?@.+?\..+)?

Demo 演示

The first line matches the name, followed by a newline. 第一行与名称匹配,后跟换行符。 The second line is optional - it matches a phone number, followed by a newline. 第二行是可选的 - 它匹配电话号码,后跟换行符。 The third line, also optional, matches the mail. 第三行也是可选的,与邮件匹配。

You may refine the subpatterns if needed, I just picked some which seemed to work with your input data. 如果需要,您可以优化子模式,我只选择了一些似乎与您的输入数据一起使用的子模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM