i have a pattern as like this 开发者_高级运维
"The world is #bright# and #beautiful#"
i need to retrieve the string "bright","beautiful" inside # # .. any pointers
My solution (thanks to Bolu):
string s = "The world is #bright# and #beautiful#";
string[] str = s.Split('#');
for (int i = 0; i <= str.Length - 1; i++)
{
if (i % 2 != 0)
{
Response.Write(str[i] + "<br />");
}
}
If all you want is the string inside ##, then no need for regex, just use string.Split:
string rawstring="The world is #bright# and beautiful";
string[] tem=rawstring.Split('#');
After that, all you need is to get the even item (with index: 1,3,5....) from the string[] tem
As long as you can't have nested #...#
sequences, #([^#]+)#
will work, and will capture the content between #'s as the first backreference.
Explanation:
# match a literal # character
( open a capturing group
[^ open a negated character class
# don't match # (since the character class is negated)
]+ close the class, match it one or more times
) close the capturing group
# match a literal # character
Check out the Match
object:
var match = Regex.Match(yourstring, @"The world is #(.*)# and beautiful")
var bright = match.Groups[1]
Of course this breaks down when you have more than two #'s in your string. Then you probably want to do a non-greedy match. This can be done with the regex "#(.*?)#
". This will match the shortest string between two sharps and still have the contents in the first group.
You need to set up a Capturing Group
by wrapping the part you want to capture in round brackets ()
and optionally specifying a name for the capture:
Regex r = new Regex(@"#([^#]+?)#");
which can be accessed by using this code:
Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups[1];
Or with a named parameter:
Regex r = new Regex(@"#(?<mycapture>[^#]+?)#");
which can be accessed by using this code:
Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups["mycapture"];
精彩评论