简体   繁体   中英

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

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"

Let me know if I should delete the old post, but perhaps someone wants to read it.

The way to do a "words to look for" inside the regex is like this:

regex = @"(Key1|Key2|Key3|LastName|FirstName|Etc):"

What you are doing probably isn't worth the effort in a regex, though it can probably be done the way you want (still not 100% clear on requirements, though). It involves looking ahead to the next match, and stopping at that point.

Here is a re-write as a regex + regular functional code that should do the trick. It doesn't care about spaces, so if you ask for "Key2" like below, it will separate it from the value.

string[] keys = {"Key1", "Key2", "Key3"};
string source = "Key1:Value1Key2: ValueAnd A: To Test Key3:   Something";
FindKeys(keys, source);

private void FindKeys(IEnumerable<string> keywords, string source) {
    var found = new Dictionary<string, string>(10);
    var keys = string.Join("|", keywords.ToArray());
    var matches = Regex.Matches(source, @"(?<key>" + keys + "):",
                          RegexOptions.IgnoreCase);            

    foreach (Match m in matches) {
        var key = m.Groups["key"].ToString();
        var start = m.Index + m.Length;
        var nx = m.NextMatch();
        var end = (nx.Success ? nx.Index : source.Length);
        found.Add(key, source.Substring(start, end - start));
    }

    foreach (var n in found) {
        Console.WriteLine("Key={0}, Value={1}", n.Key, n.Value);
    }                            
}

And the output from this is:

Key=Key1, Value=Value1
Key=Key2, Value= ValueAnd A: To Test 
Key=Key3, Value=   Something
/KeywordB\: (\w)/

This matches any word that comes after your keyword. As you didn´t mentioned any terminator, I assumed that you wanted only the word next to the keyword.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM