dhrubo_moy dhrubo_moy - 3 months ago 12
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
foo(str)
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
str1
and
str2
should return true.
str3
should return false.

I can't figure out the regular expression to match
"[DIGIT]"
.
/[[\d]]/
was the best I could come up with, which doesn't work and only matches
"N]"
, misses the starting bracket. Try it here.

Currently the method looks like this:

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

Answer

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.