tags:

views:

87

answers:

3

Hi! I have a string like a

"[echo]\r\n[echo] Building VARIANT_SETTINGS 05...\r\n[echo] VARIANT_SETTINGS file 1094_002-900208R7.0_05R01 02.hex successfully generated!\r\n"

How is it possible to get the 1094_002-900208R7.0_05R01 02.hex?

I tried to do this via Regex.Replace, but I don't understand well how it is happen. I tried

fileName = Regex.Replace(hexOutInfo, @"^.*VARIANT_SETTINGS file ([ ._0-9a-z-]+) successfully generated!.*$", "$1");

That returns to me the whole text.

+2  A: 

Use System.Text.RegularExpressions.Match.

An instance of the Match class is returned by the Regex.Match method and represents the first pattern match in a string. Subsequent matches are represented by Match objects returned by the Match.NextMatch method. In addition, a MatchCollection object that consists of zero, one, or more Match objects is returned by the Regex.Matches method.

...

If a pattern match is successful, the Value property contains the matched substring, the Index property indicates the zero-based starting position of the matched substring in the input string, and the Length property indicates the length of matched substring in the input string.

Because a single match can involve multiple capturing groups, Match has a Groups property that returns the GroupCollection. The GroupCollection has accessors that return each group. Match inherits from Group so the entire substring matched can be accessed directly. That is, the Match instance itself is equivalent to Match.Groups[0] (Match.Groups(0) in Visual Basic).

I suggest modifying the regex to match only a part of the input and to avoid multi-line match issues. The filename sub-expression needs to match both upper and lower case letters.

mypattern = Regex("VARIANT_SETTINGS file ([ ._0-9A-Za-z-]+) successfully generated!");
filename = mypattern.Match(mytext).Groups[1].Value;

filename should now be "1094_002-900208R7.0_05R01 02.hex".

gimel
A: 

You should use Regex.Match. Here is a quick and dirty solution

var str = "[echo]\r\n[echo] Building VARIANT_SETTINGS 05...\r\n" +
          "[echo] VARIANT_SETTINGS file 1094_002-900208R7.0_05R01 02.hex " + 
          "successfully generated!\r\n"

var match = Regex.Match(str, @".*\sfile\s(?<name>.*\.hex)\s.*");
Console.WriteLine(match.Groups["name"].Value);

outputs

1094_002-900208R7.0_05R01 02.hex

if you using it often you may want to compile and cache the regex. Also the pattern could be improved somewhat, but i will leave that for you to do.

Bear Monkey
A: 

A very simple way would be:

        string hexOutInfo = "[echo]\r\n[echo] Building VARIANT_SETTINGS 05...\r\n[echo] VARIANT_SETTINGS file 1094_002-900208R7.0_05R01 02.hex successfully generated!\r\n";

        string leftCrop = hexOutInfo.Replace("[echo]\r\n[echo] Building VARIANT_SETTINGS 05...\r\n[echo] VARIANT_SETTINGS file ", "");
        string hexFileName = leftCrop.Replace(" successfully generated!\r\n", "");
Ali YILDIRIM