monoy suronoy
monoy suronoy

Reputation: 911

string regex on ruby on rails

how to make sure my string format must be like this :

locker_number=3,[email protected],mobile_phone=091332771331,firstname=ucup

i want my string format `"key=value,"

how to make regex for check my string on ruby?

Upvotes: 1

Views: 136

Answers (3)

chris85
chris85

Reputation: 23892

This regex will find what you're after.

\w+=.*?(,|$)

If you want to capture each pairing use

(\w+)=(.*?)(?:,|$)

http://rubular.com/r/A2ernIzQkq

The \w+ is one or more occurrences of a character a-z, 1-9, or an underscore. The .*? is everything until the first , or the end of the string ($). The pipe is or and the ?: tells the regex no to capture that part of the expression.

Per your comment it would be used in Ruby as such,

(/\w+=.*?(,|$)/ =~ my_string) == 0

Upvotes: 1

erik258
erik258

Reputation: 16304

What about something like this? It's picky about the last element not ending with ,. But it doesn't enforce the need for no commas in the key or no equals in the value.

'locker_number=3,[email protected],mobile_phone=091332771331,firstname=ucup' =~ /^([^=]+=[^,]+,)*([^=]+=[^,]+)$/

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30995

You can use a regex like this:

\w+=.*?(,|$)

Working demo

You can use this code:

"<your string>" =~ /\w+=.*?(,|$)/

Upvotes: 0

Related Questions