Link to home
Start Free TrialLog in
Avatar of andieje
andieje

asked on

basic reg ex splitting a name into forename and surname

Hi

I don't know very much about regular expressions. How would i split a string input that represents a name into its forname and surname parts. I am assuming forenames cannot contain spaces for now so i would need to split the string into 2 parts based on the first space character in the string input. I then need each part of the regular expression in 2 separate variables. I think i would use the Match object for this but i dont know how to access the matched parts.

thanks
andrea
Avatar of Wayne Taylor (webtubbs)
Wayne Taylor (webtubbs)
Flag of Australia image

Hi Andrea,

You need not use RegExp for this, as the String object has a Split method, which returns an array of strings, using the specified delimiter....

    Dim FullName() As String = "John Smith".Split(" ")
    Dim FirstName As String = FullName(0)
    Dim Surname As String = FullName(1)

Regards,

Wayne
ASKER CERTIFIED SOLUTION
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of andieje
andieje

ASKER

hi webtubbs

won't that solution split a surname that includes a space in it too? i think green shost has provided a more accurate solution

thanks a lot
Avatar of andieje

ASKER

thanks a lot
> won't that solution split a surname that includes a space in it too?

Yes, you would only get the first and middle name:

Dim FullName() As String = "Georg von Trapp".Split(" ")

FullName(0) contains "Georg"
FullName(1) contains "von"

but:

FullName(2) contains "Trapp"

It's possible to use the split without losing the information, you can limit the split to not return more than two strings:

Dim FullName() As String = "Georg von Trapp".Split(" ".ToCharArray(), 2)

FullName(0) contains "Georg"
FullName(1) contains "von Trapp"


However, if you have a string containing more than strictly a first and last name, you can't really split it accurately if you don't have any information what the middle part is. It can be who first names like "Reginald Kenneth Dwight", a nickname like "Bernard 'Bernie' Taupin", a split last name like "Jon Bon Jovi", a title like "Georg von Trapp" or a double last name like "Frank Lloyd Wright".