Carver Stone
Carver Stone

Reputation: 105

Regex match up to first PRECEDING space from character

I have this snippet here

agent=Mozilla/5.0 (Windows NT 6.0; WOW64; Trident/6.0; rv:11.0) like Gecko custom1=custom1 custom2=custom2 more=otherstuffi dont care about etc

What I want is a regex that matches up to here

agent=Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko

I have tried this:

agent=(.*?=)

Which gives me:

agent=Mozilla/5.0 (Windows NT 6.0; WOW64; Trident/6.0; rv:11.0) like Gecko custom1=

But custom1 could be fewer or more chars sometimes.. so i don't want it to be specific I want to just get everything before the space between Gecko and custom however if the browser/os isn't exact it might not be Gecko. So I feel like the best way is to use the next = (after custom1) since it will always be there.

So if I can get up to that custom1= from the agent and then only match whats before the space before custom1, that would work.

Or am I over complicating this?

Thanks.

Upvotes: 0

Views: 241

Answers (2)

anubhava
anubhava

Reputation: 785156

You can use this regex:

agent=(.+?)\s+[^=\s]+=

And get you matched text in captured group #1

RegEx Demo

RegEx Breakup:

  • agent=: match text agent=
  • (.+?): match 1 or more characters (lazy)
  • \s+: match 1+ whitespace
  • [^=\s]+=: match 1+ non-whitespace, non-= character followed by =

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

I suggest the following:

agent=([^=]*)(?=\s)

This will match as many characters besides = as it can, but it will stop before the final space.

Test it live on regex101.com.

Upvotes: 1

Related Questions