[英]regex to find a specific word before and after any specific word in string
[英]regex to find a word before and after a specific word
我需要一个正则表达式,它可以在特定单词之前和之后给我单词,包括搜索词本身。
像:“这是一些查找单词的虚拟文本”当文本是我的搜索词时,应该给我一串“虚拟文本”。
另一个问题,提供的字符串可能包含不止一次的搜索词,因此我必须能够使用 C# 检索该字符串中的所有匹配项。
像“ This is some dummy text to find a word in a string full with text and words ” 应该返回:
编辑:实际上我应该返回所有包含搜索词的匹配项。 举几个例子: 文字读得太多了。 -> 文本是
阅读我的文字。 -> 我的文字
这是一个文本字段示例 -> 一个文本字段示例
编辑:
如果您想从第一个单词之前的空格中抓取所有内容到单词之后的空格,请使用:
(?:\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
);
比赛是:
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
*/
/[A-Za-z'-]+ text [A-Za-z'-]+/
在大多数情况下都应该有效,包括连字符和复合词。
([A-z]+) text ([A-z]+)
会做得很好
[a-zA-Z]+\stext\s[a-zA-Z]+
我相信这会很好地工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.