[英]How can I find a string after a specific string/character using regex
我對正則表達式(c#)絕望,所以我很感激一些幫助:
Basicaly我需要解析一個文本,我需要在文本中找到以下信息:
示范文本:
KeywordB:*** TextToFind *其余部分不相關但是** KeywordB: Text ToFindB然后再添加一些文本。
我需要在某個關鍵字之后找到可能以“:”結尾的單詞。
[UPDATE]
謝謝安德魯和艾倫:很抱歉重新打開這個問題,但正則表達式中缺少一個重要的東西。 正如我在上一篇評論中所寫的那樣,作為正則表達式的一部分,是否有可能有一個變量(要查找多少個單詞,具體取決於關鍵字)?
或者:我可以為每個關鍵字設置不同的正則表達式(只會是一個完整的手)。 但仍然不知道如何在正則表達式中使“要尋找的詞”不變
基本的正則表達式是這樣的:
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]);
}
如果你在一行中有多個這樣的,你可以使用:
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"]);
}
另外,請在這里查看正則表達式設計器: http : //www.radsoftware.com.au/ 。 它是免費的,我經常使用它。 它適用於原型表達式。 您需要重新安排基本工作的UI,但之后很容易。
(fyi)字符串之前的“@”意味着\\不再意味着特殊的東西,所以你可以輸入@“c:\\ fun.txt”而不是“c:\\ fun.txt”
讓我知道我是否應該刪除舊帖子,但也許有人想讀它。
在正則表達式中執行“查找單詞”的方法是這樣的:
regex = @"(Key1|Key2|Key3|LastName|FirstName|Etc):"
你正在做的事情可能不值得在正則表達式中付出努力,盡管它可能以你想要的方式完成(但仍然沒有100%明確要求)。 它涉及展望下一場比賽,並在那一點停下來。
這是一個重寫,作為正則表達式+常規功能代碼,應該做到這一點。 它不關心空格,所以如果你要求下面的“Key2”,它會將它與值分開。
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);
}
}
而這個輸出是:
Key=Key1, Value=Value1
Key=Key2, Value= ValueAnd A: To Test
Key=Key3, Value= Something
/KeywordB\: (\w)/
這匹配關鍵字后面的任何字詞。 由於你沒有提到任何終結符,我假設你只想要關鍵字旁邊的單詞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.