我试图找出正则表达式与引号中的文件名匹配的内容.例如.
blah blah rubarb "someFile.txt" blah
rubard "anotherFile.txt" blah blah
Run Code Online (Sandbox Code Playgroud)
我想要配对
someFile.txt
anotherFile.txt
Run Code Online (Sandbox Code Playgroud)
我正在使用.NET.我现在正在阅读文档,但任何帮助非常感谢.
试试这个:
(?<=")\w+\.\w+(?=")
Run Code Online (Sandbox Code Playgroud)
这不包括比赛中的引号.
注意:我用这个正则表达式做了一个假设.我假设文件名只包含一个.字符.所以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
}
Run Code Online (Sandbox Code Playgroud)
这里有一些评论可以帮助您理解它:
@"
(?<= # 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
)
"
Run Code Online (Sandbox Code Playgroud)