regex查找特定单词前后的单词

本文关键字:单词 单词前 查找 regex | 更新日期: 2023-09-27 17:54:20

我需要一个正则表达式,它在特定单词之前和之后为我提供单词,包括搜索单词本身。

比如:当text是我的搜索词时,">This is some dummy text to find a word"应该会给我一个字符串"dummytextto"。

另一个问题是,提供的字符串可能会包含不止一个搜索词,所以我必须能够用C#检索该字符串中的所有匹配项。

类似于">这是一些伪文本,用于在充满文本和单词的字符串中查找单词"应返回:

  • "伪文本到">
  • "带有文本和">

编辑:实际上,我应该返回所有包含搜索词的匹配项。举几个例子:文本太过易读。->文本为

阅读我的文字。->我的文本

这是一个文本字段示例->文本字段示例

regex查找特定单词前后的单词

编辑:

如果您想从第一个单词前的空格到单词后的空格获取所有内容,请使用:

(?:'S+'s)?'S*text'S*(?:'s'S+)?

一个简单的测试:

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
);

匹配项为:

伪文本到带有文本和文本为我的短信。文本字段示例笨蛋la@text.be到
//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
*/
/[A-Za-z'-]+ text [A-Za-z'-]+/

应该适用于大多数情况,包括连字符和复合词。

([A-z]+) text ([A-z]+)

会做得很好

[a-zA-Z]+''stext''s[a-zA-Z]+

我相信这将很好地工作