使用正则表达式从句子中的方括号中提取剩余的子字符串
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
。
我试过这个 Regex \[(.*?)\]
,它给我方括号内的整个子字符串。
我也尝试过正则表达式 \bamenities\b
来获取 Amenities 一词并尝试否定它周围的字符串。
但是,我希望子字符串的其余部分与开头的子字符串 '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
你可以试试this.
/\[amenities (.*?)\]/ig
(?<=amenities )+[^\]]*
这使用了 lookbehind
断言,这有助于替换 \K
我有这样一句话:[amenities FREE HOT BREAKFAST AND WIRELESS INTERNET]
我想从方括号中提取子字符串FREE HOT BREAKFAST AND WIRELESS INTERNET
。
我试过这个 Regex \[(.*?)\]
,它给我方括号内的整个子字符串。
我也尝试过正则表达式 \bamenities\b
来获取 Amenities 一词并尝试否定它周围的字符串。
但是,我希望子字符串的其余部分与开头的子字符串 '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
你可以试试this.
/\[amenities (.*?)\]/ig
(?<=amenities )+[^\]]*
这使用了 lookbehind
断言,这有助于替换 \K