JBoy
JBoy

Reputation: 5735

Regular exp to match string from beginning until certain char is met

I have some long string where i'm trying to catch a substring until a certain character is met. Lets suppose I have the following string, and I would like to get the text until the first ampersand.

abc.8965.aghtj&hgjkiyu5.8jfhsdj

I would like to extract what is present before the ampersand so: abc.8965.aghtj W thought this would work:

grep'^.*&{1}'

I would translate it as

^ start of string
.* match whatever chars
&{1} until the first ampersand is matched

Any advice? I'm afraid this will take me weeks

Upvotes: 0

Views: 2032

Answers (2)

user1919238
user1919238

Reputation:

{1} does not match the first occurrence; instead it means "match exactly one of the preceding pattern/character", which is identical to just matching the character (&{3} would match &&&).

In order to match the first occurrence of &, you need to use .*?:

grep'^.*?&'

Normally, .* is greedy, meaning it matches as much as possible. This means your pattern would match the last ampersand rather than the first one. .*? is the non-greedy version, matching as little as possible while fulfilling the pattern.

Update: That syntax may not be supported by grep. Here is another option:

'^[^&]*&'

It matches anything that is not an ampersand, up to the first ampersand.

You also may have to enable extended regular expression in grep (-E).

Upvotes: 2

Sergio
Sergio

Reputation: 6948

Try this one:

^.*?(?=&)

it won't get ampersand sign, just a text before it

Upvotes: 0

Related Questions