【问题标题】:Extracting the remaining substring out of square brackets in a sentence using Regex使用正则表达式从句子中的方括号中提取剩余的子字符串
【发布时间】:2018-06-24 19:14:28
【问题描述】:

我有这样一句话:[amenities FREE HOT BREAKFAST AND WIRELESS INTERNET]

我想从方括号中提取子字符串FREE HOT BREAKFAST AND WIRELESS INTERNET

我已经尝试过这个正则表达式\[(.*?)\],它给了我方括号内的整个子字符串。

我还尝试使用正则表达式 \bamenities\b 来获取“便利设施”一词,并尝试否定它周围的字符串。

但是,除了开头的子字符串 '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

【问题讨论】:

  • 为什么投反对票?

标签: c# regex string regex-negation regex-lookarounds


【解决方案1】:
(?<=amenities )+[^\]]*

这使用了lookbehind 断言,这有助于替换\K

Check the result here

【讨论】:

    【解决方案2】:

    你可以试试this

    /\[amenities (.*?)\]/ig
    

    【讨论】:

    • string s = "BEST AVAILABLE RATE , [amenities BREAKFAST] , [amenities WIFI] AND FITN ? - MORE IN HP"; MatchCollection m = Regex.Matches(s, @"/\[amenities (.*?)\]/ig"); foreach(var item in m) Console.WriteLine("{0}", item); 我试过的这段代码似乎没有得到任何输出。但是在Regex 101 site 我得到了完全匹配
    • 像这样改变你的 C# 代码:MatchCollection m = Regex.Matches(s, @"\[amenities (.*?)\]",RegexOptions.IgnoreCase);
    • 是的,在这种情况下,我将整个单词放在方括号内,就像之前的 Index=22, Value=[amenities BREAKFAST] Index=46, Value=[amenities WIFI]
    • 需要修改c#代码。 foreach(Match item in m) { Console.WriteLine("{0}", item.Groups[1].Value); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多