簡體   English   中英

如何使用方括號構建正則表達式

[英]how to build a regex with square brackets

我需要構建一個reg-ex來查找["",之間的所有字符串",

上述字符串有多次出現,我想要它們之間的所有內容。 請幫助?

這是一個例子: http//pastebin.com/crFDit2N

你的意思是一個字符串,如[" my beautiful string ",

然后它聽起來像這個簡單的正則表達式:

\[".*?",

要獲得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

你可以使用這個正則表達式:

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

它使用后視和前瞻肯定斷言來檢查匹配是否以["后跟",開頭。

@Szymon和@ zx81:

小心:你的正則表達式可能有問題(取決於xhammer的需要) 如果字符串是例如:

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

你的正則表達式會抓住["anything you want["anything you want",而不是["anything you want",

要解決此問題,您可以使用: [^\\[]代替. 在每個正則表達式中。

查看正則表達式是否適合您的需求的最佳方法是在在線正則表達式測試器中進行測試。

(PS:即使這個解決方案也不完美,以防字符串中有'['但我不知道如何在一個正則表達式中解決這種情況)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM