Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regular Expression 2

Status
Not open for further replies.

Joulius

Programmer
Dec 16, 2003
215
RO
I'm having troubles finding the regular expression to use.
I'll need this in a windows application (C#).
I have a string with the following format:
Code:
text1_page_xx[,xx],_text2
where "_" denotes a space and xx a number. Example:
Code:
This is some text page 1, and the text goes on
or
Another boring section page 14,56, continous text
What I want is to split the string into two strings:
Code:
string 1: text_page_xx[,xx]
string 2: text2
Any ideeas?

Thank you in advance!

[morning]
 
something like

([a-zA-Z0-9, ]*),([a-zA-Z0-9]*)

Should two substrings split on the last comma. You can then get the substrings from the paranthesised sub expressions of the match. I think you use $1, $2 etc in C# but would need to look it up.

Rob


Go placidly amidst the noise and haste, and remember what peace there may be in silence - Erhmann 1927
 
Sorry was bit too early in the morning when I wrote the above and I'm mixing my RegEx! Above is a hybrid Javascript/C# and is wrong anyway!

In C# you could use the capturecollection class to do this...The below is pretty close ut will need some tweaking. Unfortunately I run out of playing time so can't finish off [sad]
Code:
string s = "text1 page 12,12, text2";
  Regex r = new Regex("(?<1>[^,]*),(?<2>[^,]*)");
  Match m = r.Match(s);
  while(m.Success){
    CaptureCollection cc = m.Captures;
    foreach(Capture c in cc){
      Response.Write("Capture=[" + c + "]");
    }
    m=m.NextMatch();
}
Of course you could always do something like...
Code:
string s = "text1 page 12,12, text2";
string s1 = s.Substring(0, s.LastIndexOf(",")).Trim();
string s2 = s.Substring(s.LastIndexOf(",")+1).Trim();
Response.Write(s1 + "<br />" + s2);
and save your brain from the Regex - unless like me you quite like the pain ;-)

Rob

Go placidly amidst the noise and haste, and remember what peace there may be in silence - Erhmann 1927
 
Rob - I think your example is designed just to split by the comma, which is not specific enough.

Try these two regexs. The first captures what Julius wants as string 1. The seconds captures what he wants as string 2.

.+\spage\s\d+(,\d+)?

(?<=\spage\s\d+(,\d+)?,\s).+

Hope this helps

Mark [openup]
 
You have saved my life guys! [2thumbsup]
Rob, Mark was right - your example was designed to split the string by the comma (which I've tryed before asking), so Mark's example was the golden key.
Thank you both!

[morning]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top