Regular Expression to Accept Both Positive and Negative Numbers

What is the regex validation for positive and negative numbers?

Adding -? will do the trick:

^-?[1-9]+([0-9]+)*$

regex pattern to allow positive and negative integers

Assuming you only mention an optional negative sign in front of the number:

xs:pattern value="-?[0-9]{0,10}"

Regex to match positive or negative number or empty string, but not '-' alone

You may make the digits obligatory and enclose the whole number matching part with an optional group:

/^(?:-?\d+)?$/

See the regex demo

Details

  • ^ - start of the string
  • (?:-?\d+)? - an optional non-capturing group matching 1 or 0 occurrences of:

    • -? - an optional -
    • \d+ - 1 or more digits
  • $ - end of string.

Regex to match positive and negative numbers and text between "" after a character

You may read the file into a string and run the following regex:

var matches = Regex.Matches(filecontents, @"(?m)^\*\w+[\s-[\r\n]]*""?(.*?)""?\r?$")
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();

See the .NET regex demo.

Details:

  • (?m) - RegexOptions.Multiline option on
  • ^ - start of a line
  • \* - a * char
  • \w+ - one or more word chars
  • [\s-[\r\n]]* - zero or more whitespaces other than CR and LF
  • "? - an optional " char
  • (.*?) - Group 1: any zero or more chars other than an LF char, as few as possible
  • "? - an optional " char
  • \r? - an optional CR
  • $ - end of a line/string.


Related Topics



Leave a reply



Submit