Home > Mobile >  Get a word from a string in Ruby
Get a word from a string in Ruby

Time:09-16

I am looking for two Regex (or any better way in Ruby) that will give me specific word out of a string.

The string I have is:

<string name="animal">dog</string>

I want to take out "animal" and "dog" from the string so I need two scripts for each word. I have looked into the available options but could not find a better solution. Any help would be highly appreciated.

CodePudding user response:

It looks like XML, so XML parser would be the preferred way of handling it. Which parser to use depends on your specific requirements and environment (maybe you already have nokogiri in your Gemfile?). Here's how to proceed with ox suggested by @roo:

string = '<string name="animal">dog</string>'
parsed = Ox.parse(string)
parsed[:name] #=> "animal"
parsed.text #=> "dog"

If you really want to go with a regex for some reason (not really advisable and really fragile) you can use multiple capturing groups:

regex = /\A<string [^>]*name="([^"] )"[^>]*>([^<]*)<\/string>\z/
_, name, value = regex.match(str)
name #=> "animal"
value #=> "dog"

Note, that regex is very fragile and will just silently stop working if the xml structure changes.

  • Related