0

How would I write a regexp so that the string MUST equal the exact format in the regexp?

For example:

/\d:\d/ =~ 5:4

BUT

/\d:\d/ is also equal to 5:42alskjf2425

how do I make it so that my regexp checks for only a digit, followed by a colon, followed by a digit, and nothing else?

Thanks.

2 Answers 2

2

Use \A and \z anchors, to match the beginning and end of a string:

/\A\d:\d\z/ =~ '5:4'  # => 0   (boolean true)
/\A\d:\d\z/ =~ '5:4x' # => nil (boolean false)
Sign up to request clarification or add additional context in comments.

1 Comment

@user3329470 - if the answer is what you're looking for you can accept it by clicking the check mark next to it.
1

If you need to specify how many characters must be found, you can do it a couple ways:

  • \d finds one.
  • \d{1} finds one.
  • \d{1,2} finds one or two.
  • \d{1,} finds one or more.
  • \d{,2} finds zero, one or two.

In other words, use:

/\d{1}:\d{1}/

Check it out:

'5:4'[/\d{1}:\d{1}/]             # => "5:4"
'5:42alskjf2425'[/\d{1}:\d{1}/]  # => "5:4"

That's all documented so take the time to read through the Regexp documentation.

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.