Click here to Skip to main content
15,886,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,
In my application I want to split a string into two pieces, I know we can do that by using "Regex.Split ".But in my case the condition is little bit different.
See,
My string is "012AA23SB45AA78"
if I use Regex.Split("012AA23SB45AA78","AA") will return a string array like
012
23SB45
78
but I need just two strings one is "012AA23SB45" and the other is "78".(means split the string into two pieces where the last Regex.match occurred. Is there is any possibilities to do this using the combinations of Regex.match and Regex.Split....??

Thanks in advance
-Manuprasad M
Posted
Comments
Arjsrya 6-Jan-15 7:38am    
I don't think there is a straight forward approach.Check the length of string array and Leave the last string & concatenate other strings.
Zoltán Zörgő 6-Jan-15 7:39am    
Is there any login in the input string? The format is always xAAyAAz?

Regex.Split isn't what you need here - you are probably better going with a "stock" Match operation and using the groups, or better still, just doing it manually via LastIndexOf and Substring:
C#
string inp = "012AA23SB45AA78";
int index = inp.LastIndexOf("AA");
string start = inp.Substring(0, index);
string end = inp.Substring(index + 2);
 
Share this answer
 
Why not use a combination of string.LastIndexOf and string.Substring to do it?

Try something like this:
var firstPart = s.Substring(0, s.LastIndexOf('AA'));
var lastPart = s.Substring(s.LastIndexOf('AA') + 2);


Good luck!
 
Share this answer
 
v3
If you need everything before the last AA, you can simply use Regex.Match also, with "^(.*)AA.*$". The first group will match your substring.
 
Share this answer
 

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