正则表达式来之前和特定的单词后找到一个词 [英] regex to find a word before and after a specific word
问题描述
我需要一个正则表达式之前和特定的单词后,包括自己的搜索词,让我的字
I need a regex that gives me the word before and after a specific word, included the search word itself.
我爱:这是一些虚拟的文本找到一个字的应该给我的字符串虚拟的文本以当文本是我的搜索词。
Like: "This is some dummy text to find a word" should give me a string of "dummy text to" when text is my search word.
另外一个问题,这是可能的,所提供的更多的则字符串一旦搜索词,所以我必须能够检索该字符串使用C#的所有比赛。
Another question, it's possible that the string provided will contain more then once the search word so I must be able to retrieve all matches in that string with C#.
像的这是一些虚拟的文本来查找字符串充满文字和文字的一个字
应返回:
Like "This is some dummy text to find a word in a string full with text and words" Should return:
- 虚拟的文本以
- 是文本和
- "dummy text to"
- "with text and"
我希望任何一个可以帮助我。 !
THX
I hope any one can help me. Thx!
编辑:
我was't完成。其实我应该包含搜索词返回的所有比赛。
举几个例子:
文本阅读过。 - >文字
I was't complete. Actually I should have all the matches returned that contain the search word. A few examples: Text is too read. -> Text is
读我的文字。 - >我的文字
Read my text. -> my text
这是一个文本字段的例子 - >文本字段例如
This is a text-field example -> a text-field example
我希望现在我更清楚。 Sry基因,我并没有从一开始就解释了这一点。
I hope I'm more clear now. Sry that I didn't explained this from the start.
THX任何帮助!
推荐答案
编辑:
如果你想的抓住从空间中的所有内容第一个字的前后字空间的使用:
(?:\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
);
比赛分别是:
the matches are:
dummy text to
with text and
Text is
my text.
a text-field example
dummy la@text.be to
这篇关于正则表达式来之前和特定的单词后找到一个词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!