-3

My program should find Console.WriteLine(" in the source text box and start reading the string just after the " until it finds a "), and then store the captured string in a variable. For example, if the input is:

Console.WriteLine("Hello World")

Then the variable's value should be Hello World.

Help would be appreciated.

Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235
S. Gautam
  • 9
  • 2

1 Answers1

2
string yourInput = ...
var result = Regex.Match(yourInput, "Console.WriteLine[(]\"(.*?)(?<!\\\\)\"[)]").Groups[1].Value;

A little test:

string yourInput = "Console.WriteLine(\"\\\") Yeahhh\")"; 
yourInput += "Console.WriteLine(\"At least Regex can handle \"this\"\")";
yourInput += "Console.WriteLine(\"Although \"Regex\" is afraid of parsing \"text\" with nested elements\")";
var matches = Regex.Matches(yourInput, "Console.WriteLine[(]\"(.*?)(?<!\\\\)\"[)]");
foreach (Match m in matches)
    System.Diagnostics.Debug.Print(m.Groups[1].Value);

Output

\") Yeahhh
At least Regex can handle "this"
Although "Regex" is afraid of parsing "text" with nested elements
King King
  • 61,710
  • 16
  • 105
  • 130
  • `Console.WriteLine("\") Yeahhh")"` - regex are hard :) – Alexei Levenkov Aug 31 '13 at 02:13
  • @AlexeiLevenkov you mean that string is unable to be matched with `Regex`? I've tested it and \ is the result :) – King King Aug 31 '13 at 02:15
  • But it should be `\") Yeahhh` (Sorry I typed `"` instead of last `;`: `Console.WriteLine("\") Yeahhh");`) – Alexei Levenkov Aug 31 '13 at 02:18
  • 100% of the strings I've tried have failed. Maybe you could add what strings you've tried and how the regular expression works. – dcaswell Aug 31 '13 at 02:19
  • `@"\(""(.+)""\)"` would be sufficient. Also, @user814064 Your string literals have to look like `@"Console.WriteLine(""hello World"")"` to actually be `Console.WriteLine("Hello World")`. – Zong Aug 31 '13 at 02:19
  • @AlexeiLevenkov that's right. can't match `nested element`, but for the `OP's description`, the desired string starts from `Console.WriteLine("` to the second `"`, if he means he wants to match all the string between `(...)`, that's not possible with regex. – King King Aug 31 '13 at 02:21
  • 1
    @jdphenix Why `.+?` instead of `.+`? Also it's not a valid string (with quotes). – Zong Aug 31 '13 at 02:28
  • @ZongZhengLi I discovered my brainfart a few seconds ago, yeah back to my coffee... – jdphenix Aug 31 '13 at 02:33