Kunj
Kunj

Reputation: 77

Extracting word in with regex

I want to replace $word with another word in the following string:

"Hello $word How are you"

I used /\$(.*)/, /\$(.*)(\s)/ , /\$(.* \s)/. Due to *, I get the whole string after $, but I only need that word; I need to escape the space. I tried /s,\b, and few other options, but I cannot figure it out. Any help would be appreciated.

Upvotes: 0

Views: 67

Answers (4)

Jikku Jose
Jikku Jose

Reputation: 18804

Consider:

>> string = "Hello $word How are you"
=> "Hello $word How are you"
>> replace_regex = /(?<replace_word>\$\w+)/
=> /(?<replace_word>\$\w+)/
>> string.gsub(replace_regex, "Bob")
=> "Hello Bob How are you"
>> string.match(replace_regex)[:replace_word]
=> "$word"

Note:

  • replace_word is the regex with a named capture group.

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Substituting placeholder words for other words is usually not done with a regex but with the % method and a hash:

h = {word: "aaa", other_word: "bbb"} 
p "Hello %{word} How are you. %{other_word}. Bye %{word}" % h
# => "Hello aaa How are you. bbb. Bye aaa"

Upvotes: 0

urielable
urielable

Reputation: 31

If you only want to replace "$world" using a regex, try this:

"Hello $word How are you".gsub(/\$word/, 'other_word')

Or:

"Hello $word How are you".sub('$word',"*")

You can read more for gsub here: http://www.ruby-doc.org/core-2.2.0/String.html#method-i-gsub

Upvotes: 1

hwnd
hwnd

Reputation: 70732

* is a greedy operator meaning it will match as much as it can and still allow the remainder of the regular expression to match. The token .* will greedily match every single character in the string. The regex engine will then advance to the next token \s which matches the last whitespace before the word "you" in the string given you a result of word How are.

You can use \S in place of .* which matches any non-whitespace characters.

\$\S+

Or to simply match only word characters, you can use the following:

\$\w+

Upvotes: 4

Related Questions