regex issue

J

Junkone

my pattern should match either import or delete
However it does not seem to be working.

irb(main):014:0> pattern="([import]|[delete])"
=> "([import]|[delete])"
irb(main):015:0> pattern.match("import")
=> #<MatchData:0x2e76f9c>
irb(main):016:0> $1
=> nil
 
S

Stefano Crocco

Alle Friday 25 January 2008, Junkone ha scritto:
my pattern should match either import or delete
However it does not seem to be working.

irb(main):014:0> pattern="([import]|[delete])"
=> "([import]|[delete])"
irb(main):015:0> pattern.match("import")
=> #<MatchData:0x2e76f9c>
irb(main):016:0> $1
=> nil

I see two problems with your code:
1) if you want to check that a string (in your case, 'import') matches a
pattern, you need to use

string.match(pattern)

which, in your case, is

'import'.match(pattern)

2) in a regexp, the construct [abc] means one character among 'a', 'b' or 'c',
not (as I guess you think) the string 'abc'. Because of this, the string 'i'
matches your pattern:

'i'.match(pattern)
=> #<MatchData:0xb7bbed44>

To do what you want, you simply need:

pattern = "(import|delete")
"import".match pattern
=>#<MatchData:0xb7bb7cb0>
$1
=> "import"

I hope this helps

Stefano
 
J

Jesús Gabriel y Galán

my pattern should match either import or delete
However it does not seem to be working.

irb(main):014:0> pattern="([import]|[delete])"
=> "([import]|[delete])"
irb(main):015:0> pattern.match("import")
=> #<MatchData:0x2e76f9c>
irb(main):016:0> $1
=> nil

Try this:

irb(main):004:0> pattern=/(import|delete)/
=> /(import|delete)/
irb(main):005:0> pattern.match "import"
=> #<MatchData:0xb7cd1434>
irb(main):006:0> $1
=> "import"

Pattern should be a regular expression. Also I think you don't want
square brackets, because that means matching any one character in the
set, not the word.

Jesus.
 

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

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,744
Latest member
CortneyMcK

Latest Threads

Top