1

I am trying to make a regex expression that will validate a number that is in the range of -100 to 100. I made this regex expression: (^-[1-100]* |^[0-100]*) but it doesn't work as expected.

I am looking for a number pattern in a string, not just a number by itself.

the script:

#!/bin/bash

check(){
input="test1.txt"
while read -r line; do
a=( $line )

for i in "${a[@]:1}"; do
if [[ "$i" =~ (^-[1-100]*|^[0-100]*) ]]; then
echo "$i"
fi
done
done < "$input"
}
check

the input file:

add $s0 $s1 $s3
sub $s0 $s1
addi $s1 $s2 76
lw $s2 -50($s2)

the actual result: add $s0 $s1 $s3 sub $s0 $s1 addi $s1 $s2 76 lw $s2 -50($s2)

the expected result: 76 -50($s2).

  • Why do you absolutely want a regex for that? A regex is a good tool... for some cases but not all. Bash has numeric comparison operators. – Patrick Mevzek Mar 29 at 19:20
  • One misconception in your writing: [0-100] will not be parsed as a range from 0 to 100 like you expect, but as 3 items: 0-1, 0, 0. 0-1 will indeed be the range from 0 to 1, so all added [0-100] is the same as [0100] which is just [01] or (0|1). [1-100] will in fact be the exact same thing. [..] is for character classes so things in it are understood character by character. Also the * applies to the token before it and means the token can appear never or once or multiple times (unbounded), so your [0-100]* means in fact: empty string, or unlimited amounts of0or1. – Patrick Mevzek Mar 29 at 19:23
1

The expression [0-100] isn't a range of integers; it's a set of characters that happens to include a range 0-1 (so matches 0 or 1 or 0 or 0).

To match the range of integers -100 to 100, you could use:

  • a decimal digit [0-9]; optionally followed by
  • a second decimal digit [0-9]

or

  • the sequence 100

all preceded by an optional sign. So

^[-+]?([0-9][0-9]?|100)$

Ex.

while read num; do 
 [[ $num =~ ^[-+]?([0-9][0-9]?|100)$ ]] && echo "$num is valid" || echo "$num is invalid"
done
-101
-101 is invalid
-100
-100 is valid
-83
-83 is valid
22
22 is valid
100
100 is valid
102
102 is invalid
^C
  • when I use this expression I don't get any results – David Mar 29 at 13:06
  • 1
    @David then there are likely other issues with your code: I only tried to answer the "Negative to positive number range in regex in bash scripting" part – steeldriver Mar 29 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.