正则表达式在特定单词之前和之后找到单词

时间:2011-04-29 13:29:43

标签: c# regex

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

喜欢:“这是一些用于查找单词的虚拟文本”当文本时,应该给我一串“虚拟文字”是我的搜索词。

另一个问题是,提供的字符串可能包含多一次搜索字,因此我必须能够使用C#检索该字符串中的所有匹配项。

喜欢“这是一些虚拟文本,用于在字符串中查找带有文本和单词的单词” 应该回复:

  • “虚拟文字至”
  • “使用文字和”

修改 实际上我应该返回包含搜索词的所有匹配项。 几个例子: 文字太多了。 - >文字是

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

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

5 个答案:

答案 0 :(得分:17)

修改

如果您希望在第一个单词之前从空格中获取所有内容,请使用后的空格:

(?:\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

答案 1 :(得分:7)

//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
*/

答案 2 :(得分:2)

/[A-Za-z'-]+ text [A-Za-z'-]+/

在大多数情况下都应该有效,包括带连字符和复合词。

答案 3 :(得分:1)

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

会做得很好

答案 4 :(得分:0)

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

我相信这会很好地工作