ValeMarz
ValeMarz

Reputation: 101

How to split string in Rails with pattern?

I've a string like this "some text !11.22.33" and when i call

"some text !11.22.33".scan(/!(\w+)/)[0].join.to_s

it returns only "11". I want to return "11.22.33" so scan function has to skip dot and take all the string. How i can do that?

Upvotes: 1

Views: 375

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

If your string is always in this format, just use

"some text !11.22.33".partition('!').last

For a regex approach, you may use matching with capturing:

"some text !11.22.33"[/!([\d.]+)/, 1]

See the Ruby demo

Details:

  • ! - a literal ! symbol
  • ([\d.]+) - Capturing group 1: one or more digits or dots
  • The 1 argument tells Ruby to output only the captured value

An alternative regex is /!(\d+(?:\.\d+)*)/ that will capture 1+ digits and then 0 or more sequences of a . and 1+ digits (so, if there is a trailing dot, it won't be captured).

Upvotes: 1

Related Questions