开发者

getting a substring from a regular expression

开发者 https://www.devze.com 2022-12-10 13:51 出处:网络
Here is the line of text: SRC=\'999\' where 999 can be any three digits. I need a grep comman开发者_C百科d that will return me the 999. How do I do this?Here is how to do it using sed

Here is the line of text:

SRC='999'

where 999 can be any three digits.

I need a grep comman开发者_C百科d that will return me the 999. How do I do this?


Here is how to do it using sed

grep SRC=\'.*\' | sed 's/SRC=.\(.*\)./\1/'


You can use the -o option on grep to return only the part of the string that matches the regex:

echo "SRC='999'" | grep -o -E '[0-9]{3}'


Are the lines to match always in the format SRC='nnn' ? Then you could use

grep SRC | cut -d"'" -f2


just sed will do

$ echo SRC='999' | sed '/SRC/s/SRC=//'
999


Platform grep or general regular expression?

Regex

SRC\=\'(\d{3})\'


why grep? How about..

substr("SRC='999'",6,3)


You can't do it with plain grep. As the man page on my box states: "grep - print lines matching a pattern" grep only prints lines, not part of lines.

I would recommend awk since it can do both the pattern matching and sub-line extracting:

awk -F\' ' /SRC/ {print $2}'


depends on your platform / language.

in Ruby:

string = "SRC = '999'"

string.match(/([0-9]{3})/).to_s.to_i 

will return an integer

0

精彩评论

暂无评论...
验证码 换一张
取 消