简体   繁体   中英

Extracting full name from string using regex javascript

"Name: Roger LeftPhone: (848) 274-9377Email: rogerleft@trueworld.ai"

What is the regex expression (javascript) that I need to extract "Roger Left" from the string above?

Thanks!!

You can get the name in group 1 with this regex :

Name:\s*(.*?)Phone:

We assume here, that the name is any string which starts immediately after "Name:" and ends at "Phone:". The \\s* pattern strips away the leading spaces from the name. The : after Phone is important, because it is possible that someone will have a name including Phone , for example:

Name: Phoney ChanPhone: .....

Without : after phone we would have matched the empty string in front of Phoney .

^Name:\s(.+)Phone:\s(.+)Email:\s(.+)

This works as follows:

^Name: matches everything that starts with Name:
\\s Matches all white spaces.
(.+)Phone matches all characters until Phone

With that you can get the name. The rest is for you to get the rest of the elements in case that is needed.

If you just need the name then ^Name:\\s(.+)Phone: should be enough.

Check here for a playground

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