繁体   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