dhrubo_moy dhrubo_moy - 2 years ago 133
Ruby Question

Check if string starts with regex in ruby to match "[NATURAL NUMBER]"

Suppose I have a following strings:

str1 = "[1] : blah blah blah"
str2 = "[2] : Something"
str3 = "Nothing"

I wrote a method
that takes a string as parameter and should return true if the string starts with "[DIGIT]" where digit can be any natural number (1,2,3,4...). So
should return true.
should return false.

I can't figure out the regular expression to match
was the best I could come up with, which doesn't work and only matches
, misses the starting bracket. Try it here.

Currently the method looks like this:

def foo(str)
str =~ /[[\d]]/

Answer Source

Try this, with slash:

$> irb
>> str1 = "[1] : blah blah blah"
>> str1[/\[\d\]/]
=> "[1]"

Use the \ character to escape a character that has special meaning inside a regular expression.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download