Home > Blockchain >  Regex grab a substring from a string
Regex grab a substring from a string

Time:05-10

Anyone familiar with how to use regex grab the following expression:

Random1 `json:"random1"`
Random2 `json:"random2"`
Random3 `json:"random3"`

desired output:

random1
random2
random3

What I have tried so far:

Try one:

grep -o '(\".*?\")' example1.file 

Try two:

grep -o '\"*\"' example1.file

returned nothing

This returns everything but just want the substring:

Attempt 3

grep -E "\"(.*)\"" example1.file 

Expected output:

random1
random2
random3

CodePudding user response:

You need to use -P with lookarounds, so that the quotes won't be included in the match.

grep -o -P '(?<").*(?=")' example1.file

This requires GNU grep to get the -P option for PCRE.

CodePudding user response:

With GNU grep and a Perl-compatible regular expression:

grep -Po '(?<=").*(?=")' file

Output:

random1
random2
random3

CodePudding user response:

Using sed:

sed -E 's/^.*"(.*)"`$|.*/\1/g' example1.file
  • Related