简体   繁体   English

正则表达式匹配模式中的名称

[英]Regex matching names in pattern

I've got a simple pattern LASTNAME, FIRSTNAME MI_IDNUMBER that I've matched with ^[a-zA-Z0-9, ]+_[a-zA-Z0-9]+ .我有一个简单的模式LASTNAME, FIRSTNAME MI_IDNUMBER^[a-zA-Z0-9, ]+_[a-zA-Z0-9]+匹配。 The problem I'm running into now are records where the person has a last name with a hyphen like WALKER-REYES, ANNA T_AW12345 .我现在遇到的问题是该人姓氏带有连字符的记录,例如WALKER-REYES, ANNA T_AW12345 I've tried incorporating something like (?=\\S*['-])([a-zA-Z'-]+) into it but this only identifies that LASTNAME in the string.我试过将诸如(?=\\S*['-])([a-zA-Z'-]+)合并到其中,但这只能识别字符串中的LASTNAME What's the best way to string this all together?将这一切串在一起的最佳方法是什么? Not all names will have hyphens.并非所有名称都带有连字符。

The way you built your regex is not optimal.您构建正则表达式的方式不是最佳的。 You are matching every character, including space, until you find an underscore ( _ ) and then match the rest.您正在匹配每个字符,包括空格,直到找到下划线 ( _ ),然后匹配其余字符。 Rather than doing that, you shouldn't match spaces and have every part of your string in different groups.而不是这样做,您不应该匹配空格并将字符串的每个部分放在不同的组中。

You can try using this regex, which support hyphens.您可以尝试使用这个支持连字符的正则表达式。

^(?: ?([a-zA-Z0-9\-]+),?){2} ([a-zA-Z0-9_]+)

正则表达式可视化

You can test more cases at this regex101您可以在此 regex101 上测试更多案例

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

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