1

How can we extract the words from a string in rubular expression?

$0Public$robotics00$india0$000facebook

If we want to extract the words Public robotics india facebook from the above string, how can we?

I am using ([^0$]), but it is giving the letters not the proper words.

Tanish Gupta
  • 400
  • 2
  • 8
  • 20

2 Answers2

1

We can try a regex split here:

input = "$0Public$robotics00$india0$000facebook"
parts = input.split(/\d*\$\d*/)
puts parts

This prints:

Public
robotics
india
facebook
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

You can match $ followed by optional zeroes, and use a capture group to match the characters other than $ 0 or a whitespace char

\$0*([^0$\s]+)

Explanation

  • \$ Match a $ char
  • 0* Match optional zeroes
  • ( Capture group 1
    • [^0$\s]+ Match 1+ times any char except 0 $ or a whitespace char
  • ) Close group 1

Regex demo

re = /\$0*([^0$\s]+)/
str = '$0Public$robotics00$india0$000facebook
'

# Print the match result
str.scan(re) do |match|
    puts match.first
end

Output

Public
robotics
india
facebook
The fourth bird
  • 154,723
  • 16
  • 55
  • 70