You are not logged in.

#1 2009-12-24 10:17:38

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,403
Website

Regex help

Here is my simplified problem...

> teststring="foo=1 foo=('1' '2' \ '3') foo=\"1 2 3\""
> echo $teststring
foo=1 foo=('1' '2' \ '3') foo="1 2 3"

I want to extract the value for these variables (in reality they will not be all "foo"s)...

#brackets
> echo $teststring | grep -o "foo=([^)]*)"
foo=('1' '2' \ '3')
#quotes
> echo $teststring | grep -o "foo=\"[^)]*\""
foo="1 2 3"
#value
> echo $teststring | grep -o "foo=[^\s\(\"]"
foo=1
#all at once...
> echo ${teststring} | grep -o -e "foo=[^\s\(\"]" -e "foo=\"[^)]*\"" -e "foo=([^)]*)"
foo=1
foo=('1' '2' \ '3')
foo="1 2 3"

Now I want to "simply" the grep by combining the regexp...  but this fails:

> echo ${teststring} | grep -o -e "foo=([^\s\(\"]|\"[^)]*\"|([^)]*))"

Any hints at what I am doing wrong.  Also, I do not want to use awk, perl, ...   bash and grep are all.

Offline

#2 2009-12-24 10:37:40

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Regex help

This works tho:

echo ${teststring} | grep -Eo "foo=([^\s\(\"]|\"[^)]*\"|\([^)]*\))"

Edit: and this:

echo ${teststring} | grep -o -e "foo=\([^\s\(\"]\|\"[^)]*\"\|([^)]*)\)"

The existence of multiple Regexp Standards can be a pain...

Last edited by lolilolicon (2009-12-24 10:41:58)


This silver ladybug at line 28...

Offline

#3 2009-12-24 10:45:16

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,963
Website

Re: Regex help

Damn, too slow

echo $teststring | grep -o -e "foo=\([^\s\(\"]\|\"[^)]*\"\|([^)]*)\)"

Anyway, you need to escape the capturing parenthesis and the pipe: \(   \|   \)


@lolilolicon
Yep, multiple standards, with multiple escape requirements etc can drive you crazy.


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

#4 2009-12-24 20:06:18

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,403
Website

Re: Regex help

Thanks...    I could not figure this out for the life of me!   I had figured that I did not need to escape brackets I normally needed to escape with "grep -e" but did not think I would have to escape others!

Offline

#5 2009-12-27 17:58:13

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Regex help

I'd recommend using grep -P. It's usually faster and more robust than the other versions, oddly.

Offline

#6 2009-12-28 21:50:36

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,403
Website

Re: Regex help

Daenyth wrote:

I'd recommend using grep -P. It's usually faster and more robust than the other versions, oddly.

Hmmm.... from the man page

This is  highly experimental and grep -P may warn of unimplemented features.

I think I will stick with -E for the time being.

Offline

Board footer

Powered by FluxBB