簡體   English   中英

那個正則表達式怎么樣?

[英]How would that regular expression be?

我有一個遵循一些規則的表達式:

  • 角色'必須是第一個和最后一個角色
  • ''內部可能有零個或多個空格
  • 內部可能有零或多% ''
  • ''里面可以有零個或多個單詞(字母和數字)

表達:

(?i)^(?<q>['])[%\p{Zs}\p{L}\p{N}|()]*\k<q>$

現在我需要另一個表達式來替換所有)和(例如,在“TEST”的字符串中,但僅當它們沒有被''包圍時。訣竅是當時)或(被''包圍但是這些字符屬於一對不同的'',它不應該通過。

結果示例:

    '(' > pass
    ' ( ' > pass
    ')'   > pass
    ' ) '   > pass
    ' content here ' ' )'  > pass
    ' content here' ) ' another content'  > does not pass

請注意,第一個內容有'',第二個內容也有。 任何)或(如果它介於它們之間,則不應通過)。

我不是正則表達式的專業人士,所以如果你不知道它是怎么回事,任何相關的文檔或教程都會有很大的幫助。

你可以使用正則表達式:

^.*[()](?=[^']*'(?>(?:[^']*'[^']*){2})*$)

演示

碼:

var rgxHardNut = new Regex(@"^.*[()](?=[^']*'(?>(?:[^']*'[^']*){2})*$)");
var check1 = rgxHardNut.IsMatch("'('");  // true
var check2 = rgxHardNut.IsMatch("' ( '");// true
var check3 = rgxHardNut.IsMatch("')'");  // true
var check4 = rgxHardNut.IsMatch("' ) '");// true
var check5 = rgxHardNut.IsMatch("' content here ' ' )'"); // true
var check6 = rgxHardNut.IsMatch("' content here' ) ' another content'"); // false

我認為應該這樣做:

Regex regex = new Regex(@"^'[^']*?'(?:(?:[^()]*)'[^']*?')*$");

編輯演示

class Program
{
    static void Main(string[] args)
    {
        Regex regex = new Regex(@"^'[^']*?'(?:(?:[^()]*)'[^']*?')*$");

        string shouldPass1 = "'('";
        string shouldPass2 = "' ( '";
        string shouldPass3 = "')'";
        string shouldPass4 = "'('";
        string shouldPass5 = "' content here ' ' )'";
        string shouldFail = "' content here' ) ' another content'";

        Console.WriteLine("Pass1 : {0}",regex.IsMatch(shouldPass1));
        Console.WriteLine("Pass2 : {0}", regex.IsMatch(shouldPass2));
        Console.WriteLine("Pass3 : {0}", regex.IsMatch(shouldPass3));
        Console.WriteLine("Pass4 : {0}", regex.IsMatch(shouldPass4));
        Console.WriteLine("Pass5 : {0}", regex.IsMatch(shouldPass5));
        Console.WriteLine("Fail : {0}", regex.IsMatch(shouldFail));

        string wholeThing = string.Format(
            "{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
            shouldPass1,
            shouldPass2,
            shouldPass3,
            shouldPass4,
            shouldPass5,
            shouldFail);

        Console.WriteLine("Alltogether (should fail too): {0}", regex.IsMatch(wholeThing));
    }
}

或者沒有正則表達式( Tim Schmelter會為我感到驕傲):

private static bool IsMatch(string text)
{
    bool result = text[0] == '\'' && text[text.Length - 1] == '\'';
    bool opened = false;

    for (int i = 0; result && i < text.Length; i++)
    {
        char currentchar = text[i];

        if (currentchar == '\'')
        {
            opened = !opened;
        }
        if (!opened && (currentchar == '(' || currentchar == ')'))
        {
            result = false;
        }
    }

    return result;
}

暫無
暫無

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

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