简体   繁体   中英

regular expression to extract number from string

I want to extract number from string. This is the string

#all/30

All I want is 30 . How can I extract? I try to use :

echo "#all/30" | sed 's/.*\/([^0-9])\..*//'

But nothing happen. How should I write for the regular expression? Sorry for bad english.

You may consider using grep to extract the numbers from a simple string like this.

echo "#all/30" | grep -o '[0-9]\+'
  • -o option shows only the matching part that matches the pattern.

You could try the below sed command,

$ echo "#all/30" | sed 's/[^0-9]*\([0-9]\+\)[^0-9]*/\1/'
30
  • [^0-9]* [^...] is a negated character class. It matches any character but not the one inside the negated character class. [^0-9]* matches zero or more non-digit characters.
  • \\([0-9]\\+\\) Captures one or more digit characters.
  • [^0-9]* Matches zero or more non-digit characters.
  • Replacing the matched characters with the chars inside group 1 will give you the number 30
echo "all/30" | sed 's/[^0-9]*\/\([0-9][0-9]*\)/\1/'

Avoid writing '.*' as it consumes entire string. Default matches are always greedy .

echo "all/30" | sed 's/[^0-9]*//g'
# OR
echo "all/30" | sed 's#.*/##'
# OR
echo "all/30" | sed 's#.*\([0-9]*\)#\1#'

without more info about possible input string we can only assume that structure is #all/ followed by the number (only)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM