如何捕获引号内的文件名以及后面的数字作为命名捕获(正则表达式/C#)?
Files("fileone.txt", 5969784, "file2.txt", 45345333)
在字符串中的每次出现中,能够捕获“fileone.txt”和后面的整数(循环循环每对)
我正在尝试使用这个https://regex101.com/r/MwMzBo/1但在没有“[”和“]”的情况下存在匹配问题。
需要能够将每个文件名+大小作为一对循环并移动到下一个。
感谢任何帮助!
更新
string file = "Files(\"fileone.txt\", 5969784, \"file2.txt\", 45345333, \"file2.txt\", 45345333)";
var regex = new Regex(@"(?:\G(?!\A)\s*,\s*|\w+\()(?:""(?<file>.*?)""|'(?<file>.*?)')\s*,\s*(?<number>\d+)");
var match = regex.Match(file);
var names = match.Groups["file"].Captures.Cast<Capture>();
var lengths = match.Groups["number"].Captures.Cast<Capture>();
var filelist = names.Zip(lengths, (f, n) => new { file = f.Value, length = long.Parse(n.Value) }).ToArray();
foreach (var item in filelist)
{
// Only returning 1 pair result, ignoring the rest
}
读取 match.Value 以确认正在读取的内容。仅拾取第一对。
while (match.Success)
{
MessageBox.Show(match.Value);
match = match.NextMatch();
}
现在我们可以正确得到所有结果。我读到,Regex.Match 只返回第一个匹配的结果。这解释了很多。
最佳答案
你可以使用
(?:\G(?!\A)\s*,\s*|\w+\()(?:""(?<file>.*?)""|'(?<file>.*?)')\s*,\s*(?<number>\d+)
请参阅regex demo
详细信息:
-
(?:\G(?!\A)\s*,\s*|\w+\()
- 上一次成功匹配的结尾以及用零个或多个空格括起来的逗号,或者一个单词和一个开头(
字符 -
(?:""(?<file>.*?)""|'(?<file>.*?)')
-"
,将"file"组捕获尽可能少的除换行符之外的任何零个或多个字符,然后"
,或'
,将"file"组捕获尽可能少的除换行符之外的任何零个或多个字符,然后'
-
\s*,\s*
- 用零个或多个空格括起来的逗号 -
(?<number>\d+)
- 组“数字”:一位或多位数字。
关于c# - 正则表达式如何匹配 2 个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010610/