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)?
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With