c# - Having a false-match with a regular expression, don't know how to fix -
I'm trying to detect patterns:
string "bp" For example:
-
BP 1.0 3.5/ Em>
BP-1E- 3 0.72 3.7 1.22e2
Double to detect, using pattern Me <> [+ \ -] ? (?: 0 | [1- 9] \ d *) (?: \. \ D *)? (?: [EE] [+ \ -]? D +)? which I have received from.
Unfortunately after testing some wires, I found out that my code fails to discriminate when string bp either 2 or 4 numbers here is some test case :
zero 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 a double var shortPattern = String.Join ("capture", "mpaces", "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, short-pattern, regex option. IgnoreCase); Var bpLong = Regex.Match (teststring, longpatar, reggaeopsation.gnore case); If (bpLong.Success) {Console.WriteLine ("long pattern detected"); // !! FALSE-MATCH !! } If (bpShort.Success) {Console.WriteLine ("Small pattern detected"); }} In this example, the code is matching even if only two numbers ( -1.23e4 and 5.67 ) Has 4 different numbers ( -1.23e4 , 5. , 6 , 7 ) for
Maybe I want to capture all the numbers on sub-elements or should I point out that a double issue with a whites or end-of-string, I do not know?
It is rather obvious to make a regex always find as many matches as possible So if you search for four numbers, then regex will do the best to split the string such that the four numbers are matched.
To solve the problem, you need to apply spaces between two matches .
It can be done by place:
var mspaces = @ "\ s *"; By By:
var mspaces = @ "\ s +"; ( one or more verus * from + means zero or more , so the regedx can decide not to use space between two numbers.)
You must also remove the initial spaces in the regedge insertion. Replace with:
string .join ("", mspaces, "bp" ... By:
< Code> string.joint ("", "bp" ... plus mspaces . In that case, someone gets it.
Perhaps you do not want to match stars like ABP 1 5 because there should be some space between A and BP . In the case, you can use @ "\ b" .
Finally, the argument of @MetBurland is that any pat with four numbers साथ There is a pattern with two digits.If you want your string for end , you can finally use $ if you want To start with BP , you can type the string ^ in front.
Comments
Post a Comment