Adam
Adam

Reputation: 69

Regular expression, everything until a pattern

I am looking to write a regular expression that groups on a specific pattern. For example for the string:

"File=ZZZZZZZZZZZZZZ QQQQQQQQQQ.txt size=ten check=true test=true"

I would like groups of:

File=ZZZZZZZZZZZZZZ QQQQQQQQQQ.txt
size=ten
check=true
test=true

Normally I could just look for spaces but if my file name has a space in it then this doesn't work. So I need to match everything until I hit any character plus an =.

Upvotes: 0

Views: 104

Answers (1)

cHao
cHao

Reputation: 86505

You could split by [ ](?=\w+=). The stuff in parentheses is a "lookahead assertion", and will match a space only if whatever's following it looks like a parameter.

If you're intent on matching rather than splitting, (?:[^ ]| (?!\w+=))+ should work. The (?!...) part is a negative lookahead assertion, so the space will only match if whatever follows doesn't look like a param.

Note, not all regex engines support lookahead assertions. Most do, particularly PCRE-flavored ones...but check your regex engine's docs for the proper syntax.

(Also: i'm using [ ] because Markdown hates leading spaces in inline code. You could just use a space there instead (without the brackets), or \s if you want to allow any whitespace char to separate params.)

Upvotes: 2

Related Questions