Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a string for a substring

Tags:

string

c#

regex

(Apologies, I'm very new to c#)

Given the following string:

SELECT * FROM TABLE WHERE sDATE ='~~Date~~' AND sName = '~~Some NAME~~'

I need to extract Date & Some NAME from the above string into an array.

  • It's not always going to be Date and Some NAME inside the ~~
  • There maybe a single ~~x~~ in the string, there maybe two or more
  • ~~x~~ could be any length and may contain numbers, letters and spaces
  • ~~x~~ will always start and end with ~~
  • ~~x~~ may or may not be in quotes

For a given string I'd like to get an array of the found values. I'd be OK with ~~Date~~ or just Date

I'm thinking this might be a regex situation. I've looked at .Split, .IndexOf, .Contains but none of those get me what I'm looking for since I'm not always looking for the same substring.

Update:

This is not strictly for SQL parsing, that's just a quick example. A string could also be

My name is ~~Some NAME~~ and I'm hunting for some help

like image 688
Jason Avatar asked Aug 30 '26 12:08

Jason


1 Answers

Given your description, something like (and assuming there are no ~~ inside the string you want to capture):

~~(.*?)~~

would give you the text between a pair of ~~ in a capture group. You could change . to something more restrictive if you want to.

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 of *? versus just * here. * by itself is greedy and will match as much as possible. So it would return Date~~' AND sName = '~~Some NAME because it'll take everything between the first and the last ~~. Adding the ? makes it lazy.

like image 112
Matt Burland Avatar answered Sep 01 '26 02:09

Matt Burland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!