简体   繁体   中英

Java Regular Expression repeated group capture

I am getting problem capturing a repeated group here, Can anyone help?

String : Ushinski KD (Konstantin Dmitrievich)

The regex I'm using is this :

(?i)(.*)((?:[a-z]{1,2}\.\s)+)\(.*

But it is capturing "Ushinski K. " as group 1 and "D. " as group 2. However my target is to capture "Ushinski " as group 1 and "KD " as group 2. Any help is highly appreciated.

regex demo

If your 'first name' has no space :

(?i)(\S*)\s*((?:[a-z]{1,2}\.\s)+)\(.*

I advice you to use this website for your regular expressions : https://regex101.com/

edit : if it has space but no '.':

(?i)([^\.]+)\s+((?:[a-z]{1,2}\.\s)+)\(.*

You have to use (.*?) or you can use Word Boundaries (\\b.*\\b) instead of (.*) take a look at this post What is the difference between the regex (.*?) and (.*)?

(?i)(.*?)\s((?:[a-z]{1,2}\.\s)+)\(.*

or

(?i)(\b.*\b)\s((?:[a-z]{1,2}\.\s)+)\(.*

regex demo 1

regex demo 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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