Finding a string for a substring
(Apologies, I am very new to C #)
Given the following line:
SELECT * FROM TABLE WHERE sDATE ='~~Date~~' AND sName = '~~Some NAME~~'
I need to extract Date
and Some NAME
from the above string into an array.
- It won't always be Date and Some NAME inside
~~
- There may be one per line
~~x~~
, perhaps two or more -
~~x~~
can be of any length and can contain numbers, letters and spaces -
~~x~~
always starts and ends with~~
-
~~x~~
may or may not be quoted
For a given string, I would like to get an array of found values. I would be fine with ~~Date~~
or justDate
I think it might be a regex situation. I looked at .Split
, .IndexOf
, .Contains
but none of them did not get me, I'm looking for, so I do not always look for the same string.
Update:
This is not strictly for parsing SQL, this is just a quick example. The string can also be
My name is ~~Some NAME~~ and I'm hunting for some help
Given your description, something like (and assuming that inside the string you want to capture is not ~~
):
~~(.*?)~~
will give you text between the pair ~~
in the capture group. You can change .
to something more restrictive if you like.
Example: https://dotnetfiddle.net/t6i7rx
var s = "SELECT * FROM TABLE WHERE sDATE ='~~Date~~' AND sName = '~~Some NAME~~'";
Regex r = new Regex(@"~~(.*?)~~");
foreach (Match m in r.Matches(s)) {
Console.WriteLine(m.Groups[1]);
}
Outputs:
Date
Some NAME
Note the importance *?
versus just *
here. *
itself is greedy and will match as much as possible. Therefore he will return Date~~' AND sName = '~~Some NAME
, because he will occupy everything between the first and the last ~~
. The addition ?
makes it lazy.