簡體   English   中英

使用正則表達式從句子中的方括號中提取剩余的子字符串

[英]Extracting the remaining substring out of square brackets in a sentence using Regex

我有這樣的一句話: [amenities FREE HOT BREAKFAST AND WIRELESS INTERNET]

我想從方括號中提取子字符串“ FREE HOT BREAKFAST AND WIRELESS INTERNET ”。

我已經嘗試過此正則表達式\\[(.*?)\\] ,它為我提供了方括號內的整個子字符串。

嘗試過正則表達式

我也嘗試過使用正則表達式\\bamenities\\b來獲得Amenities一詞,並嘗試取反周圍的字符串。

嘗試過Regex 2

但是,我希望其余子字符串除了開頭的子字符串'Amenities'之外。 我想在方括號中提取所有可能的子字符串,並在其前面加上'Amenities'一詞。

我正在嘗試這段代碼來提取C#中的以下內容。

 public class Program
    {
        public static void Main(string[] args)
        {
            string s = "BEST AVAILABLE RATE , [amenities BREAKFAST] , [amenities WIFI] AND FITN ? - MORE IN HP";

            MatchCollection m = Regex.Matches(s, @"\bamenities\b");

            foreach(var item in m)
                Console.WriteLine("{0}", item);

        }
    }

以下是預期

   Input: BEST AVAILABLE RATE , [amenities BREAKFAST] , [amenities WIFI] AND FITN ? - MORE IN HP 

    Output: 
    string 1 - BREAKFAST 
    string 2 - WIFI

你可以試試這個

/\[amenities (.*?)\]/ig
(?<=amenities )+[^\]]*

這使用了后lookbehind斷言,有助於替換\\K

在這里檢查結果

暫無
暫無

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

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