Regex for an upper case word in ruby

I am not very good at regex, so thanks for any help here.

I need to parse a string, for example "Sign me for LUNCH", to output the word in uppercase. I am using Ruby.

So I need something like

string = "sign me up for LUNCH"
keyword = string.gsub(/some_rexex/, '')
# keyword should == 'LUNCH'

Thanks again for your help

+4
source share
2 answers

Use the string.scanfunction instead string.gsubto capture the desired line.

> "sign me up for LUNCH".scan(/\b[A-Z]+\b/)[0]
=> "LUNCH"

\b called the word boundary, which coincides between the word symbol and a symbol other than the word.

OR

> "sign me up for LUNCH".scan(/(?<!\S)[A-Z]+(?!\S)/)[0]
=> "LUNCH"
  • (?<!\S) A negative lookbehind that claims that a non-spatial character will not precede a match.
  • [A-Z]+ .
  • (?!\S) , , .
+2

Avinash Raj . , .

, .

string = "sign me up for LUNCH"
string.split(" ").each do |word|
    if (word == word.upcase)
        puts word
    end
end 

, - , .

0

Source: https://habr.com/ru/post/1568780/


All Articles