简体   繁体   English

如何使用方括号构建正则表达式

[英]how to build a regex with square brackets

I need to build a reg-ex to find all strings between [" and ", 我需要构建一个reg-ex来查找["",之间的所有字符串",

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 这是一个例子: http//pastebin.com/crFDit2N

You mean a string such as [" my beautiful string ", ? 你的意思是一个字符串,如[" my beautiful string ",

Then it sounds like this simple regex: 然后它听起来像这个简单的正则表达式:

\[".*?",

To get all the strings in C#, you can do something like 要获得C#中的所有字符串,您可以执行类似的操作

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

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 : @Szymon和@ zx81:

Be careful : there can be a problem with your regex (depending of xhammer needs) . 小心:你的正则表达式可能有问题(取决于xhammer的需要) 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", 你的正则表达式会抓住["anything you want["anything you want",而不是["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) (PS:即使这个解决方案也不完美,以防字符串中有'['但我不知道如何在一个正则表达式中解决这种情况)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM