I'm trying to detect the pattern:
The string "BP" followed by either 2 or 4 double values (that I later want to capture) all separated by whitespaces.
For instance:
BP 1.0 3.5
BP -1e-3 0.72 3.7 1.22e2
To detect double, I'm using the pattern [+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?
which I obtained from here.
Unfortunately after testing a few strings, I discovered that my code fails to discriminate when then string BP
is followed by either 2 or 4 numbers. Here is some test case:
void Main()
{
var testString = "BP -1.23e4 5.67";
var mspaces = @"\s*"; // meaning as many spaces as you want
var cdouble = @"([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)"; // meaning capture a double
var shortPattern = String.Join("", mspaces, "BP", mspaces, cdouble, mspaces, cdouble, mspaces);
var longPattern = String.Join("", mspaces, "BP", mspaces, cdouble, mspaces, cdouble, mspaces, cdouble, mspaces, cdouble, mspaces);
var bpShort = Regex.Match(testString, shortPattern, RegexOptions.IgnoreCase);
var bpLong = Regex.Match(testString, longPattern, RegexOptions.IgnoreCase);
if (bpLong.Success)
{
Console.WriteLine("Long pattern detected"); // !!FALSE-MATCH!!
}
if (bpShort.Success)
{
Console.WriteLine("Short pattern detected");
}
}
In this example, even if there are only two numbers (-1.23e4
and 5.67
), the code is matching for 4 different numbers (-1.23e4
, 5.
, 6
, 7
)
Maybe I'm wrong adding enclosing parenthesis to indicate I want to capture all number sub-elements or maybe should I further indicate that a double ends with either whitespace or end-of-string, I don't know ?