Pergunta

I need to build a reg-ex to find all strings between [" and ",

There are multiple occurrences of both the above strings and i want all content between them. Help please?

here is an example : http://pastebin.com/crFDit2N

Foi útil?

Solução

You mean a string such as [" my beautiful string ", ?

Then it sounds like this simple regex:

\[".*?",

To get all the strings in C#, you can do something like

using System;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
class Program {

static void Main() {
string s1 = @" ["" my beautiful string "", ["" my second string "", ";
var resultList = new StringCollection();
try {
    var myRegex = new Regex(@"\["".*?"",", RegexOptions.Multiline);
    Match matchResult = myRegex.Match(s1);
    while (matchResult.Success) {
        resultList.Add(matchResult.Groups[0].Value);
        Console.WriteLine(matchResult.Groups[0].Value);
        matchResult = matchResult.NextMatch();
    } 
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

Console.WriteLine("\nPress Any Key to Exit.");
Console.ReadKey();
} // END Main
} // END Program

Outras dicas

You can use this regex:

(?<=\[").*?(?=",)

It uses look-behind and look-ahead positive assertions to check that the match is preceded by [" and followed by ",.

@Szymon and @zx81 :

Be careful : there can be a problem with your regex (depending of xhammer needs). If the string is for example :

["anything you want["anything you want",anything you want

Your regex will catch ["anything you want["anything you want", and not ["anything you want",

To solve this problem, you can use : [^\[] instead of the . in each regex.

The best way to see if a regex works for your needs is to test it in an online regex tester.

(PS : Even this solution isn't perfect in case there can be '[' in the string but I don't see how to solve this case in only one regex)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top