Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET REGEX Get Integer ONLY , exclude WHOLE DECIMAL

Tags:

.net

regex

I have a sample string '((1/1000)*2375.50)'

i want to get the 1 and 1000 which is an INT

I tried this REGEX expression:

  • -?\d+(\.\d+)? => this matches 1, 1000, and 2375.50
  • -?\d+(?!(\.|\d+)) = > this matches 1, 1000, and 50
  • -?\d+(?!\.\d+&(?![.]+[0-9]))? => 1, 1000, 2375, and 50

What expression do I have to use to match (1 and 1000)?

like image 859
Bienvenido Omosura Avatar asked Sep 29 '16 05:09

Bienvenido Omosura


2 Answers

So basically you need to match sequences of digits that are not preceded or followed by a decimal point or another digit? Why not try just that?

[TestCase("'((1/1000)*2375.50)'", new string[] { "1", "1000" })]
[TestCase("1", new string[] { "1" })]
[TestCase("1 2", new string[] { "1", "2" })]
[TestCase("123 345", new string[] { "123", "345" })]
[TestCase("123 3.5 345", new string[] { "123", "345" })]
[TestCase("123 3. 345", new string[] { "123", "345" })]
[TestCase("123 .5 345", new string[] { "123", "345" })]
[TestCase(".5-1", new string[] { "-1" })]
[TestCase("0.5-1", new string[] { "-1" })]
[TestCase("3.-1", new string[] { "-1" })]
public void Regex(string input, string[] expected)
{
    Regex regex = new Regex(@"(?:(?<![.\d])|-)\d+(?![.\d])");
    Assert.That(regex.Matches(input)
            .Cast<Match>()
            .Select(m => m.ToString())
            .ToArray(),
        Is.EqualTo(expected));
}

Seems to work.

like image 101
Sergei Tachenov Avatar answered Sep 25 '22 14:09

Sergei Tachenov


You can use:

(?<!\.)-?\b\d+\b(?!\.)

Working example

  • (?<!\.) - No period before the number.
  • -? - Optional minus sign
  • \b\d+\b - The number. Wrapped in a word boundary, so it will not be possible to match withing another number (for example, do not match 1234 in 12345.6). This will not match 2 in 2pi.
  • (?!\.) - No period after the number.
like image 27
Kobi Avatar answered Sep 24 '22 14:09

Kobi