1

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?

5
  • I think it would be something like \w+=.*?(,|$). I don't know in Ruby though how you'd compose that. Commented Jun 11, 2015 at 23:27
  • 1
    The regex is easy enough, but where is this string coming from, looks like it should be a hash Commented Jun 11, 2015 at 23:30
  • Yeah, it really pays to use a solid data format for this kind of thing - such as JSON. Otherwise you end up having to deal with goofy scenarios like equals signs or commas in the keys or values. Commented Jun 11, 2015 at 23:36
  • 1
    you right @chris85, thanks regex in ruby : (/\w+=.*?(,|$)/ =~ my_string) == 0 Commented Jun 11, 2015 at 23:36
  • Thanks, wasn't sure what that looked like in Ruby. Is this all set, should I post that as an answer? Commented Jun 11, 2015 at 23:41

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a regex like this:

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

Working demo

You can use this code:

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

Comments

0

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' =~ /^([^=]+=[^,]+,)*([^=]+=[^,]+)$/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.