Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

c# - How can I find a string after a specific string/character using regex

I am hopeless with regex (c#) so I would appreciate some help:

Basicaly I need to parse a text and I need to find the following information inside the text:

Sample text:

KeywordB:***TextToFind* the rest is not relevant but **KeywordB: Text ToFindB and then some more text.

I need to find the word(s) after a certain keyword which may end with a “:”.

[UPDATE]

Thanks Andrew and Alan: Sorry for reopening the question but there is quite an important thing missing in that regex. As I wrote in my last comment, Is it possible to have a variable (how many words to look for, depending on the keyword) as part of the regex?

Or: I could have a different regex for each keyword (will only be a hand full). But still don't know how to have the "words to look for" constant inside the regex

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The basic regex is this:

var pattern = @"KeywordB:s*(w*)";
    s* = any number of spaces
    w* = 0 or more word characters (non-space, basically)
    ()  = make a group, so you can extract the part that matched

var pattern = @"KeywordB:s*(w*)";
var test = @"KeywordB: TextToFind";
var match = Regex.Match(test, pattern);
if (match.Success) {
    Console.Write("Value found = {0}", match.Groups[1]);
}

If you have more than one of these on a line, you can use this:

var test = @"KeywordB: TextToFind KeyWordF: MoreText";
var matches = Regex.Matches(test, @"(?:s*(?<key>w*):s?(?<value>w*))");
foreach (Match f in matches ) {
    Console.WriteLine("Keyword '{0}' = '{1}'", f.Groups["key"], f.Groups["value"]);
}

Also, check out the regex designer here: http://www.radsoftware.com.au/. It is free, and I use it constantly. It works great to prototype expressions. You need to rearrange the UI for basic work, but after that it's easy.

(fyi) The "@" before strings means that no longer means something special, so you can type @"c:fun.txt" instead of "c:fun.txt"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...