简体   繁体   中英

regex to split string with option stubstrings, into three

I have asked a few regex related questions on here, and am learning a lot from the answers, but every now and then, I hit something that just stumps me. This is one of those times!

I have a load of strings (all of which are single line), that I want to break up into three parts. However, some of the parts are optional.

To simplify this example, I will use people's names. Lets assume I have the following names

Mr Homer Simpson
Mrs Marge Simpson Esq
Mr Homer Simpson Junior Esq
Bart Simpson
Lisa Simpson Esq
Maggie Simpson Junior Esq

Using a replace function , I would want to separate these into Prefix, Name and Suffix. With the list above, I would expect to see

"Mr"    "Homer Simpson"    ""
"Mrs"   "Marge Simpson"    "Esq"
"Mr"    "Homer Simpson"    "Junior Esq"
""      "Bart Simpson"     ""
""      "Lisa Simpson"     "Esq"
""      "Maggie Simpson"   "Junior Esq"

The closest I can get is the following, which obviously is way off

((Mr|Mrs)\\s)?(.*?)((Senior|Junior)?(?:\\sEsq)?)

Can anyone assist?

Thanks

Although it looks like you might have answered you own question i had already started having ago:

^(Mrs?)?\s?(\w+\s\w+)\s((Junior|Senior)?\s?Esq)?

The above assumes that names will always be two words.

Example execution: http://regexr.com?387u1

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