【发布时间】:2021-12-30 21:33:53
【问题描述】:
以下模式匹配以 'v' 开头的行,后跟任意数量的浮点数:
const RegexOptions options = RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant;
var regex = new Regex(@"^\s*v((?:\s+)[-+]?\b\d*\.?\d+\b)+$", options);
const string text = @"
v +0.5 +0.5 +0.5 0.0 1.0 1.0
v +0.5 -0.5 -0.5 1.0 0.0 1.0
v -0.5 +0.5 -0.5 1.0 1.0 0.0
v -0.5 -0.5 +0.5 0.0 0.0 0.0
";
using var reader = new StringReader(text);
for (var s = reader.ReadLine(); s != null; s = reader.ReadLine())
{
if (string.IsNullOrWhiteSpace(s))
continue;
var match = regex.Match(s);
if (match.Success)
{
foreach (Capture capture in match.Groups[1].Captures)
{
Console.WriteLine($"'{capture.Value}'");
}
}
}
它按预期工作,只是它在数字前包含前导空格:
' +0.5'
' +0.5'
' +0.5'
' 0.0'
' 1.0'
' 1.0'
...
问题:
如何忽略每个捕获数字的前导空格?
【问题讨论】:
-
您的文件结构是否始终有效,或者是否存在与您想要的模式不匹配的行?即,是否只是从有效文件中取出所有数字,还是您需要进行有效性检查并希望忽略无效行?
-
不应该有错误的内容,但有自己保护总是好的。
-
那么如果遇到像
v 1.0 xy 1.0这样的行完全忽略它会怎样? -
是的,这是无效的,实际上它是一个 Wavefront Obj 文件。