Click to See Complete Forum and Search --> : Regex
Fadel_Saraireh
February 23rd, 2006, 01:47 AM
Hi gentlemen,
Could anyone help me with Regex? I need to seach for blocks of text. For example: The #brown fox# jumped over #the fence#. I want Regex to return two macthes: #brown fox and #the fence#. I used #.+# but it matches the whole string between the pound signs.
I appreciate your help.
jhammer
February 23rd, 2006, 02:26 AM
Just a suggestion:
string s = "The #brown fox# jumped over #the fence#";
string[] nouns = s.Split("#");
you will get an array containing the following strings: "The ", "brown fox", " jumped over ", "the fence" .
Now you can get all the even indexes in the array.
Fadel_Saraireh
February 23rd, 2006, 03:17 AM
Thanks jhammer. It works fine when the "#" is not the first character in the string. I used the string methods but the code became too complicated and I think Regex is more efficient especially when the text is quite long.
MadHatter
February 23rd, 2006, 04:19 AM
Regex r = new Regex(@"[#](?<block>([a-zA-Z0-9 ])+)[#]", RegexOptions.ExplicitCapture);
foreach(Match m in r.Matches("The #brown fox# jumped over #the fence#.")) {
Console.WriteLine(m.Groups["block"].Value);
}
you might want to put more in the allowed range (like commas, or other punct. marks).
this captures text between the #'s to "block", and you should be able to extract it like that.
Fadel_Saraireh
February 23rd, 2006, 04:24 AM
For anyone who wants to know the answer: I downloaded a program called "Regexbuddy" and it helped me figure out the problem. Here is the answer:
string SubjectString = "The #brown fox# jumped over #the fence#.";
MatchCollection matches = Regex.Matches(SubjectString, "#.[^#]+#");
It returns only "brown fox" and "the fence".
However, I'm not quit sure whether this code is effecient or not. Any suggestions to improve it?
Thanks.
Fadel_Saraireh
February 23rd, 2006, 04:42 AM
Thanks MadHatter,
I tried your method and it returned the same matches.
MadHatter
February 23rd, 2006, 05:01 AM
the expression you posted is fine too, and if I had to guess would run faster since it doesnt allocate & store results like the one i posted does. you'll be fine either way.
torrud
February 23rd, 2006, 08:15 AM
Hi gentlemen,
Could anyone help me with Regex? I need to seach for blocks of text. For example: The #brown fox# jumped over #the fence#. I want Regex to return two macthes: #brown fox and #the fence#. I used #.+# but it matches the whole string between the pound signs.
I appreciate your help.
You only forgot a ? for not expansive search. ;)
string SubjectString = "The #brown fox# jumped over #the fence#.";
MatchCollection matches = Regex.Matches(SubjectString, "#.+?#");
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.