匹配单词后的单词

时间:2011-12-13 11:30:47

标签: c# regex .net-2.0 word match

我想知道,是否可以使用正则表达式匹配特定单词后的单词?例如,假设您有一个这样的字符串:

test abcde  
dummy test fghij

是否有可能获得包含测试后的单词的字符串数组(abcde和fghij)?如果是的话,你能解释一下吗?

5 个答案:

答案 0 :(得分:3)

不要使用RegEx,而应使用简单的yourString.Split(' ');

然后,你可以:

var strings = yourString.Split(' ');

var afterTest = strings.Skip(strings.IndexOf("test"))

它会更快,更简单,更安全。

另请阅读Jeff Atwood's entry about regex

答案 1 :(得分:3)

以下是我的建议:

(?:test\s)(?<word>\b\S+\b)

<强>解释

(?:test\s)       matches "test" with a trailing blank, but does not include it in the capture
(?<word>\b\s+\b) matches a word with any character except a whitspace. It will stored in a groupd called "word"

以下是一些如何使用它的示例:

var regex = new Regex(@"(?:test\s)(?<word>\b\S+\b)");
var matchCollection = regex.Matches("test abcde   dummy test fghij ");

foreach (Match match in matchCollection)
{
    Debug.WriteLine(match.Groups["word"].Value);
}

答案 2 :(得分:2)

您可以使用模式(?<=test).+的正面观察。

var matches = Regex.Matches("test abcd\ndummy test fghij", @"(?<=test).+");

答案 3 :(得分:1)

ArrayList aWrods = new ArrayList();

string[] sArr = yourString.Split(' ');
for (int i=0; i<sArr.Count()-1; i++)
    if (sArr[i] == "test")
        aWords.Add(sArr[i+1]);

答案 4 :(得分:0)

Maybe this answer can help

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

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