[英]Extracting the remaining substring out of square brackets in a sentence using Regex
I have a sentence of this kind: [amenities FREE HOT BREAKFAST AND WIRELESS INTERNET]
我有这样的一句话:
[amenities FREE HOT BREAKFAST AND WIRELESS INTERNET]
I want to extract the sub-string FREE HOT BREAKFAST AND WIRELESS INTERNET
from the square brackets. 我想从方括号中提取子字符串“
FREE HOT BREAKFAST AND WIRELESS INTERNET
”。
I have tried this Regex \\[(.*?)\\]
which is giving me the entire sub-string inside the square bracket. 我已经尝试过此正则表达式
\\[(.*?)\\]
,它为我提供了方括号内的整个子字符串。
I have also tried the Regex \\bamenities\\b
to get the word Amenities and tried to negate the string around it. 我也尝试过使用正则表达式
\\bamenities\\b
来获得Amenities一词,并尝试取反周围的字符串。
But, I want the rest of the substring apart from the substring 'Amenities'
at the start. 但是,我希望其余子字符串除了开头的子字符串
'Amenities'
之外。 I want to extract all the possible substrings in square brackets which is preceded by the word 'Amenities'
. 我想在方括号中提取所有可能的子字符串,并在其前面加上
'Amenities'
一词。
I am trying this code to extract the following in C#. 我正在尝试这段代码来提取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);
}
}
Below is what is expected 以下是预期
Input: BEST AVAILABLE RATE , [amenities BREAKFAST] , [amenities WIFI] AND FITN ? - MORE IN HP
Output:
string 1 - BREAKFAST
string 2 - WIFI
你可以试试这个 。
/\[amenities (.*?)\]/ig
(?<=amenities )+[^\]]*
This uses the lookbehind
assertion, which helps replacing \\K
这使用了后
lookbehind
断言,有助于替换\\K
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.