简体   繁体   中英

Java regular expression for checking inputed names

I know regular expressions aren't necessarily the best tool for the job, but I was wondering whether this would be possible with Java regexen:

Let's say I have a data set with names separated by line breaks like so:

John Doe  
Jane Roe  
Richard Miles  

(there are naturally a lot more names in the actual system)

I'll be reading in data where I'll get both the first and the last name separately, but they won't necessarily be in the same order.

Now, the question is, is there any way to construct a regex for, say, Richard Miles that would match both "Miles Richard" and "Richard Miles"? I know there are plenty of other ways to do this, but I'm specifically looking for a regex-based solution (not because it's necessarily practical, but I'd find it interesting)

Edit for clarification : what I mean is that I need a regex for, say, "Richard Miles" that will match on both "Richard Miles" and "Miles Richard", and preferably not just (Richard Miles|Miles Richard) because where's the fun in that?

This is in no way supposed to be practical, I'm merely interested whether regexen can do something like this.

Does it need to be complex and clever? I mean this would work.

\b(Miles Richard|Richard Miles)\b

Yes, take a look at this: -

^(\\w+)\\s(\\w+)$

It will match a word at the beginning (^\\\\w+) , followed by a space (\\\\s) , followed by another word at the end (\\\\w+$)

Are you looking for this only?

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