Click here to Skip to main content
15,897,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Given the names "Mr. John P. Doe Jr." and "Mr John P. Doe Jr", what RegEx replace pattern could be used to remove Mr. or Mr from the front of the name, and what replace pattern could be used to remove Jr. or Jr from the end of the name? My current code for eliminating name prefixes looks like this, but it's not working:
VB
'--populate array with a bunch of possible prefixes
Dim lsArrayPrefix As String() = New String() {"mr", "mrs", "miss", "dr", "prof"}

'--loop through the array looking for matches using regexp
For intCounter = 0 To UBound(lsArrayPrefix)
    pattern = "^" & lsArrayPrefix(intCounter) & "\.?\s+"
    Regex.Replace(strName, pattern, "")
Next
Posted

1 solution

Try something like:
^(mr|mrs|miss|dr|prof)[\.\s]*
 
Share this answer
 
Comments
PeteKipe 1-Aug-14 13:44pm    
It's not working for me, OG. I tried running it against names that begin "Mr.", "Mr", "mr." and "mr", but the statement Regex.Replace(strName, pattern, "") doesn't cause strName to change. The string "pattern" is set to "^(mr|mrs|miss|dr|prof)[\.\s]*". Is the pattern sensitive to case? Also, what about a period after the prefix -- will that be handled, or do I need to add additional tests to the pattern?
PeteKipe 1-Aug-14 13:56pm    
...and as I mentioned in my original question, I also need a pattern to eliminate trailing suffixes, like "Jr", "Sr", etc. Thanks in advance!
OriginalGriff 1-Aug-14 14:16pm    
You do realize that Regex.Replace returns a string with the modifications, just like string.Replace?
Remember, strings are immutable...
PeteKipe 2-Aug-14 1:20am    
Oops, had my head where the sun don't shine... It's working perfectly, and I figured out how to handle suffixes on my own. Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900