vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Wednesday, November 2, 2011

Regular Expression for separate a string


HI..Here I have to share an regular expression usage for split text from string…..Normally we can split a string some character .In some cases we have mix with number of characters…For that situation we can use regex expression to separate a string….
Here some example…
(test1) “"test2"” ANY(test) AND(test) (raj:test5 AND Test=test6) &animaltiger&
For this word we want to separate as each word we use reular expression
(test1)
“"test2"”
 ANY(test)
AND(test)
(raj:test5 AND Test=test6)
&animaltiger&
By using regex we can separate like above….
The Code as follows…….
VB CODE
Dim result As New List(Of String)
        Dim str As String
        str = "(test1) ""test2"" ANY(test) AND(test) (raj:test5 AND Test=test6) &animaltiger&"
        Dim t As MatchCollection = Regex.Matches(str, "[""].+?[""]|[^\s]*?[(].+?[)]|[&].+?[&]")
        For Each itm As Match In t
            result.Add(itm.Value)
        Next
C# code
  List<string> result = new List<string>();
            string s = @"(test1) ""test2"" ANY(test) AND(test) (raj:test5 AND Test=test6) &animaltiger&";
           
            MatchCollection t = Regex.Matches(s, @"[""].+?[""]|[^\s]*?[(].+?[)]");
           
            foreach (Match  itm in t)
            {
                result.Add(itm.Value);
            }
I hope this one helpful to all

0 comments:

Post a Comment