0

I have a regex, that I'm trying to use in Ruby. Here is my Regex, and it works in Java when I add the double escape keys

\(\*(.*?)\*\) 

I know this is a simple question, but how would I write this as a ruby expression and set it equal to a variable? I appreciate any help.

1
  • It'd help us check for correctness, if you'd supply some samples of what you expect it to match, and not match. Commented Nov 13, 2012 at 15:53

3 Answers 3

2

try this:

myregex = /\(\*(.*?)\*\)/

To be clear, this is just to save the regex to a variable. To use it:

"(**)" =~ myregex
Sign up to request clarification or add additional context in comments.

Comments

0

Regular expressions are a native type in Ruby (the actual class is "Pattern"). You can just write:

mypat = /\(\*(.*?)\*\)/

[Looks like anything between '(' / ')' pairs, yes?]

You can then do

m = mypat.match(str)
comment = m[1]

...or, more compactly

comment = mypat.match(str)[1]

1 Comment

The actual class, in MRI 1.8 and 1.9, is Regexp.
0

try this:

if /\(\*(.*?)\*\)/ === "(*hello*)"
  content = $1 # => "hello"
end

http://rubular.com/r/7eCuPX3ri0

2 Comments

I think you mean =~ rather than ==
Ah, it is === or =~ indeed

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.