Match doesn't match

V

Volkan Civelek

arg1 = "(1)a"
arg2 = "(1)a"

if arg1.match(arg2)
puts "Matched"
else
puts "Don't Matched"
end


gives me "Don't Matched" ??

Regards,
Volkan
 
A

Alexandru Popescu

arg2 should be escaped as () has a meaning in regexps.

arg2 = "\\(1\\)a"

p "match" if arg1.match(arg2)

hth,

/alex
 
M

Mike Stok

arg1 = "(1)a"
arg2 = "(1)a"

if arg1.match(arg2)
puts "Matched"
else
puts "Don't Matched"
end


gives me "Don't Matched" ??

That's because parentheses are special in a pattern, and that's what
the String#match expects as an argument. You can use Regexp.escape
to escape special characters:

mike$ irb --prompt simple=> #<MatchData:0x34d6ac>

Hope this helps,

Mike

--

Mike Stok <[email protected]>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
 
M

Morton Goldberg

Try it with

arg1 = "(1)a"
arg2 = '\(1\)a'

The problem is that arg2 is converted to a regular expression by
"match" and "(" and ")" are special characters in regular expressions
and, therefore, must be escaped.

Regards, Morton
 
B

benjohn

arg2 should be escaped as () has a meaning in regexps.
arg2 = "\\(1\\)a"

p "match" if arg1.match(arg2)

Possibly, Volkan Civelek, you simply wanted to see if the two string
were equal? In that case you would do:

arg1 = "(1)a"
arg2 = "(1)a"

if arg1 == arg2
puts "Matched"
else
puts "Don't Matched"
end

Cheers,
Benj
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top