我需要一个正则表达式,它在特定单词之前和之后给出了单词,包括搜索单词本身.
喜欢:" 这是一些用于查找单词的虚拟文本 "当文本是我的搜索词时,应该给我一串"虚拟文本 " .
另一个问题是,提供的字符串可能包含多一次搜索字,因此我必须能够使用C#检索该字符串中的所有匹配项.
就像" 这是一些虚拟文本,用字符串中的单词找到一个单词 "应返回:
编辑: 其实我应该返回包含搜索词的所有匹配项.举几个例子:文字太多了. - >文字是
阅读我的文字. - >我的文字
这是一个文本字段示例 - >一个文本字段示例
Ale*_*lex 17
编辑:
如果你想在第一个单词之后从空格中获取所有内容到单词 use 之后的空格:
(?:\S+\s)?\S*text\S*(?:\s\S+)?
Run Code Online (Sandbox Code Playgroud)
一个简单的测试:
string input = @"
This is some dummy text to find a word in a string full with text and words
Text is too read
Read my text.
This is a text-field example
this is some dummy la@text.be to read";
var matches = Regex.Matches(
input,
@"(?:\S+\s)?\S*text\S*(?:\s\S+)?",
RegexOptions.IgnoreCase
);
Run Code Online (Sandbox Code Playgroud)
比赛是:
dummy text to with text and Text is my text. a text-field example dummy la@text.be to
//I prefer this style for readability
string pattern = @"(?<before>\w+) text (?<after>\w+)";
string input = "larry text bob fred text ginger fred text barney";
MatchCollection matches = Regex.Matches(input, pattern);
for (int i = 0; i < matches.Count; i++)
{
Console.WriteLine("before:" + matches[i].Groups["before"].ToString());
Console.WriteLine("after:" + matches[i].Groups["after"].ToString());
}
/* Output:
before:larry
after:bob
before:fred
after:ginger
before:fred
after:barney
*/
Run Code Online (Sandbox Code Playgroud)