문제

I have a string like this

ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH

How do I retrieve the string between $ and /$?

Expected string should be

  1. ToBeFetched1

  2. ToBeFetched2

도움이 되었습니까?

해결책

Regex r = new Regex(Regex.Escape("-$") + "(.*?)"  + Regex.Escape(@"/$"));
                MatchCollection matches = r.Matches("ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH");
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Groups[1].Value);
            }

Here this will work for sure.

다른 팁

Since you have "open" and "close" markers, the regex expression would obviously be built around this form:

[head-marker: $] [the content you are interested in: anything] [tail-marker: /$]

so, with addition of a parentheses to form a capturing group:

$(.*)$

However, two problems here: * expressions are greedy (and you dont want it to be, as you want all smallest matches possible) - so it has to be weakened, and also the $ is a special character in regex, so it has to be escaped:

\$(.*?)/\$

this forms almost-good expression. It will however falsely match agains such input:

aaaaa/$bbbbb/$ccccc    ->    bbbbb

because the "head-marker" can skip the slash and hit the first dollar sign what most probably you wouldn't want. Hence, some lookbehind would be useful here too:

(?!</)\$(.*?)/\$

The ?!<XXXX instructs to match only if XXXX does not precede the potential match.

See also MSDN: Regex syntax and operators

edit: actually Arie's suggestion is much simplier as it doesn't use capturing group. Note the small difference though: Arie's example explicitely fobids the data to contain a dollar sign, so ABCD$-$ToBeFe$tched1/$- will result in tched1 not ToBeFe$tched1. If you need the latter, just change the inner [^$] part. Think and pick what you actually need!

Using String Methods:

string s ="ABCD$-$ToBeFetched1/$-$ToBeFetched2/$-EF$GH";

var results = s.Split('-')
               .Where(x=> x.StartsWith("$") && x.EndsWith("/$"))
               .Select(y=> y.Substring(1,y.Length - 3));

//Console.WriteLine("string1: {0}, string2:{1}",results.ToArray());

(?<=\$)[^$]{1,}(?=/\$)

(?<=\$) - positive lookbehind: it ensurers your match starts right after $ ($ not included in the match)

[^$]{1,} - matches characters other than $; {1,} instead of * to ensure there will be no empty matches (for strings lilke "$/$")

(?=/\$) - positive lookahead: it ensures your match ends right before /$ (/$ not included in the match)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top