• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Regex for Reversing Last Name, First Name?

 
Ranch Hand
Posts: 231
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there,

Suppose I have a String which is similar to this:



How can I use a regex to turn it into:



Sincerely,

James
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The search string for would be something like "(.*), (.*)", and the replacement string would be something like "\\2 \\1". The exact syntax depends on the regex package you're using, but that's the general idea. You may have to escape the parentheses with backslashes, and probably want to make the search string more selective (and guard against several commas).
 
James Dekker
Ranch Hand
Posts: 231
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ulf,

Thanks for replying!

I am fairly new to Java Regex. Am using the one which comes with JDK 1.5.

Don't really understand some of your tips, being a Java Regex newbie ...

This is what I have so far:



How does one suggest reversing "Smith, Joe" to "Joe Smith", and also what if someone puts a middle name, e.g.: "Smith, Joe E.", so it would become "Joe E. Smith"?

Sincerely,

James
 
author
Posts: 23958
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You don't actually have to use the regex engine directly... you could just use the string regex convenience methods. Try...



Henry
 
James Dekker
Ranch Hand
Posts: 231
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry!

That explains it!

Cheers,

James
 
keep an eye out for scorpions and black widows. But the tiny ads are safe.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic