我试图找出正则表达式与引号中的文件名匹配的内容。例如
blah blah rubarb "someFile.txt" blah
rubard "anotherFile.txt" blah blah
我想匹配
someFile.txt
anotherFile.txt
我正在使用.NET。我现在正在阅读文档,但任何帮助都非常感激。
答案 0 :(得分:5)
试试这个:
(?<=")\w+\.\w+(?=")
这不包括比赛中的引号。
注意:我对这个正则表达式做了一个假设。我假设文件名只包含一个.
字符。因此my.file.txt
将不匹配。如果您需要匹配,请告诉我,我会更新它。
下面介绍如何在c#代码中使用它来迭代所有匹配。
try {
Regex regexObj = new Regex(@"(?<="")\w+\.\w+(?="")");
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
// matched text: matchResults.Value
// match start: matchResults.Index
// match length: matchResults.Length
matchResults = matchResults.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
以下是一些可以帮助您理解的评论:
@"
(?<= # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
"" # Match the character “""” literally
)
\w # Match a single character that is a “word character” (letters, digits, and underscores)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\. # Match the character “.” literally
\w # Match a single character that is a “word character” (letters, digits, and underscores)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
(?= # Assert that the regex below can be matched, starting at this position (positive lookahead)
"" # Match the character “""” literally
)
"
答案 1 :(得分:2)
这将匹配非空白字符加上文件名中的3-4个字符扩展名。
\"(\S+\.\w{3,4})\"
答案 2 :(得分:1)
试试这个:
\"(\w+\.\w+)\"
提示:请记住逃避\
s ...