tags:

views:

74

answers:

3

I want to extract all values from the text line below using regular expressions:

(Sales (Type 0 0 0 0 000 0 0 0 0) "Product" "ProductType" "" "0000" "0000") ;;ProductName 000

How to write regular expression for this? am using C#.

am using the following code to read the text file

 string expr = @"^\(Sales \(Type \d \d((?: \d+){7})\) "([^"]+)" "([^"]+)" "" "(\d+)" "(\d+)"

";
Regex regex = new Regex(expr);

        using (StreamReader r = new StreamReader(@"C:\records.log"))
        {

            while ((line = r.ReadLine()) != null)
            {


                foreach (Match m in regex.Matches(line))
                {
                   string value = m.Value.Trim();
                   MessageBox.Show(value);
                }
            }
        }

is it right? but i cant get the value

A: 

Maybe you can split on [( ";]+, that is, one or more parenthesis, spaces, quotes or semicolons.

Sjoerd
+1  A: 

Hi,

This could be useful, enter in the string you want the regular expression generated for and it will generate the RegEx in the selected language. http://txt2re.com/

Liam

Liam
+1  A: 
^\(Sales \(Type \d \d((?: \d+){7})\) "([^"]+)" "([^"]+)" "" "(\d+)" "(\d+)"

matches these values in your sample string

  • match group 1: ' 0 0 000 0 0 0 0' (trim contents and split on space to get individual values)
  • match group 2: 'Product'
  • match group 3: 'ProductType'
  • match group 4: '0000'
  • match group 5: '0000'

You could also just split the entire string on space and pick the parts you want, entirely without regex. However, regular expressions make sure the string looks right, whereas a simple split does not.

Tomalak
@Tomalak, How i can use this regex to split my values.???
deep
@deep: You use `String.Split()` to split your values.
Tomalak
@ plz look my updated question, i just new to regex, am using the above code to read, but i cant get the values.??
deep
@deep: Look at the numbered match groups.
Tomalak
ya thanks i got
deep