简体   繁体   English

从字符串中提取数字的正则表达式

[英]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 . 我只想要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. 您可以考虑使用grep从这样的简单字符串中提取数字。

echo "#all/30" | grep -o '[0-9]\+'
  • -o option shows only the matching part that matches the pattern. -o选项仅显示与模式匹配的匹配部分。

You could try the below sed command, 您可以尝试以下sed命令,

$ echo "#all/30" | sed 's/[^0-9]*\([0-9]\+\)[^0-9]*/\1/'
30
  • [^0-9]* [^...] is a negated character class. [^0-9]* [^...]是一个否定的字符类。 It matches any character but not the one inside the negated character class. 它匹配任何字符,但不匹配否定字符类中的任何字符。 [^0-9]* matches zero or more non-digit characters. [^0-9]*匹配零个或多个非数字字符。
  • \\([0-9]\\+\\) Captures one or more digit characters. \\([0-9]\\+\\)捕获一个或多个数字字符。
  • [^0-9]* Matches zero or more non-digit characters. [^0-9]*匹配零个或多个非数字字符。
  • Replacing the matched characters with the chars inside group 1 will give you the number 30 将匹配的字符替换为组1中的字符将得到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) 没有更多关于可能的输入字符串的信息,我们只能假设结构为#all/后跟数字(仅)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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