alians
alians

Reputation: 3

how to use regex to split a format string?

I want to use regex to split some string like this @key='value' to key and value.

my regex is [^@'=]+[^'=], the output is good when the length of key and value is > 1, but sometimes when the length is only 1 char, the output is not correct.

Can anybody suggest improvements for my regex?

Upvotes: 0

Views: 148

Answers (3)

Indy9000
Indy9000

Reputation: 8851

^@[A-Za-z0-9]+\s*=\s*'[A-Za-z0-9\s]+'

This captures 
@Key = 'value'
@key='value' 
@k = 'value'

etc..

Upvotes: 1

Andrew Cheong
Andrew Cheong

Reputation: 30273

If you'd like to capture the key and value, you might try this:

/^@([^=]+)='([^']+)'$/

Then you will have the key in $1 and the value in $2.

EDIT:

I think I see what you're doing. Change your regex simply to [^@'=]+ to see the difference. However we can't tell help you unless you tell us what language you're using and some sample code.

Upvotes: 1

John Sobolewski
John Sobolewski

Reputation: 4572

\A@([^=]+)='([^']+)'  

will work as the regex but it doesn't take into account escaping of the apostrophe. this is 2 capture groups... \A says start of string... then @ then group.... (not= one or more) =' Group( not ' ) followed by '

Upvotes: 0

Related Questions