以下模式匹配以“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'
...
題:
如何忽略每個捕獲數字的前導空格?
uj5u.com熱心網友回復:
您可以更改正則運算式以匹配空白字符而不是捕獲。
這部分(?:\s )與 just 相同\s ,當您使用 1 個或多個 whitspace 字符重復該模式時,您可以省略\b末尾的單詞邊界。
請注意,在C#\d 可以匹配更多的比[0-9]
^\s*v(?:\s ([- ]?\b\d*\.?\d )) $
C# 中的行將是:
var regex = new Regex(@"^\s*v(?:\s ([- ]?\b\d*\.?\d )) $", options);
輸出
' 0.5'
' 0.5'
' 0.5'
'0.0'
'1.0'
'1.0'
' 0.5'
'-0.5'
'-0.5'
'1.0'
'0.0'
'1.0'
'-0.5'
' 0.5'
'-0.5'
'1.0'
'1.0'
'0.0'
'-0.5'
'-0.5'
' 0.5'
'0.0'
'0.0'
'0.0'
uj5u.com熱心網友回復:
你可能把這個問題復雜化了。我建議只使用以下正則運算式模式:
[ -]?\d (?:\.\d )?
您更新的 C# 代碼:
var regex = new Regex(@"[ -]?\d (?:\.\d )?", options);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/361179.html
上一篇:字串上的簡單正則運算式
