开发者

Can someone tell me why this regular expression isnt working?

开发者 https://www.devze.com 2023-04-06 10:30 出处:网络
I\'m using this regex to validate a开发者_JS百科 scientific notation in a textbox but it\'s not working. This is not allowing to type anything.

I'm using this regex to validate a开发者_JS百科 scientific notation in a textbox but it's not working. This is not allowing to type anything.

regex = new Regex("[-+]?(0?|[1-9][0-9]*)(\\.[0-9]*[1-9])?([eE][-+]?(0|[1-9][0-9]*))?");

Thanks in advance.


The problem is that your regular expression matches the empty string. An easy solution could be to add ^ in front and $ at the end to require the entire input string to match the regular expression.

Here is a small test:

var numbers = new[] {
  "0", "1", "01", "+1", "-1", "+0", "-0", "1.9", "1.09", "1.90", "1e0", "1e01", "1e10"
};
var regex = new Regex("^[-+]?(0?|[1-9][0-9]*)(\\.[0-9]*[1-9])?([eE][-+]?(0|[1-9][0-9]*))?$");
var valid = numbers
  .Select(n => regex.Match(n))
  .Where(m => m.Success)
  .Select(m => m.Value);

Printing out the elements in valid will result in the following:

0
1
+1
-1
+0
-0
1.9
1.09
1e0
1e10

Notice how 01, 1.90 and 1e01 doesn't match but I guess that is intentional.


Are you sure that this is what you're actually trying to do?

Here's a screenshot from RegexBuddy:

Can someone tell me why this regular expression isnt working?


Here's another tester that I find very useful: http://gskinner.com/RegExr/ If you're just looking to match a floating point number that includes scientific notation while capturing the exponent, then try this: [-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)? (From http://www.regular-expressions.info/floatingpoint.html)


[-+]?(0|[1-9])[0-9]*([.][0-9]*)?([eE][-+]?(0|[1-9])[0-9]*)?

is somewhat closer to what you want.... but maybe it would help if you gave an test set of expressions you expect to pass/fail

0

精彩评论

暂无评论...
验证码 换一张
取 消