Home > Enterprise >  Regular expression to capture both integer and float in bash
Regular expression to capture both integer and float in bash

Time:11-17

Can anyone help to capture the both int and float vaules using reg expression

I have below reg exp which will capture only int values but need to modify this for foot value also

'^[[:space:]]*([[:digit:]] )[[:space:]]*([kmg])b?[[:space:]]*$'

This works if the value is eg 23 MB but failing for 23.789 MB.

'^[[:space:]]*([[:digit:].] )[[:space:]]*([kmg])b?[[:space:]]*$'

CodePudding user response:

You can use

^[[:space:]]*([0-9] ([.][0-9] )?)[[:space:]]*([kmgKMG][bB]?)[[:space:]]*$

Details:

  • ^ - start of string
  • [[:space:]]* - zero or more whitespaces
  • ([0-9] ([.][0-9] )?) - Group 1: one or more digits and then an optional Group 2 matching a . and then one or more digits
  • [[:space:]]* - zero or more whitespaces
  • ([kmgKMG][bB]?) - Group 3: k, m, g, K, M or G and then an optional b or B
  • [[:space:]]* - zero or more whitespaces
  • $ - end of string.

See this regex demo.

CodePudding user response:

Assuming that the string containing your number is stored in variable vstring, the following should do:

if [[ $vstring =~  ([ -]?[[:digit:]] ([.][[:digit:]] )?) ]]
then
  number=${BASH_REMATCH[1]}
else
  echo No number in $vstring 1>&2
fi

This also assumes that a floating point has not exponential part.

  • Related