.NET REGEX Get ONLY the Whole, exclude ALL DECIMAL

I have an example string '((1/1000)*2375.50)'

I want to get 1 and 1000 which are int

I tried this REGEX expression:

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

Which expression should be used to match ( 1 and 1000 )?

+5
source share
3 answers

So basically you need to match sequences of numbers 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.

+4
source

You can use:

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

Working example

  • (?<!\.) - There is no period before the number.
  • -? - Additional minus sign
  • \b\d+\b is the number. It is wrapped at the word boundary, so it will not be possible to match another number (for example, not match 1234 to 12345.6 ). This will not match 2 in 2pi .
  • (?!\.) - There is no period after the number.
+3
source

Try the following:

  string pattern = @"\(\(([\d]+)\/([\d]+)\)\*"; string input = @"'((1/1000)*2375.50)'"; foreach (Match match in Regex.Matches(input, pattern)) { Console.WriteLine("{0}", match.Groups[1].Value); Console.WriteLine("{0}", match.Groups[2].Value); } 
+1
source

Source: https://habr.com/ru/post/1257425/


All Articles