tags:

views:

44

answers:

3

I have the following data

Animals = Dog Cat Turtle \
          Mouse Parrot \
          Snake

I would like the regex to construct a match of just the animals with none of the backslashes: Dog Cat Turtle Mouse Parrot Snake

I've got a regex, but need some help finishing it off.

/ANIMALS\s*=\s*([^\\\n]*)/
+3  A: 

Since you specified a language, I need to ask you this: Why are you relying on the regex for everything? Don't make the problem harder than it has to be by forcing the regex to do everything.

Try this approach instead...

  1. Use gsub! to get rid of the backslashes.
  2. split the string on any whitespace.
  3. Shift out the first two tokens ("Animals", "=").
  4. Join the array with a single space, or whatever other delimiter.

So the only regex you might need is one for the whitespace delimiter split. I don't know Ruby well enough to say exactly how you would do that, though.

Platinum Azure
+1 agreed. Use the right tool for the job. Not everything needs regex.
JoshD
Because the data is lot more simplified than what I stated. I can't use gsub! because I'm parsing a whole file. This was just a small snippet of sample text.
elmt
A: 

Make sure you are matching with ignore-case, because ANIMALS will not match Animals without it.

simplemotives
+1  A: 

How 'bout the regex \b(?!Animals\b)\w+\b which matches all words that aren't Animals? Use the scan method to collect all such matches, e.g.

matchArray = sourceString.scan(/\b(?!Animals\b)\w+\b/)
Eamon Nerbonne
Thanks, this isn't quite exactly what I needed but it helped put me in the right direction.
elmt