JmG
JmG

Reputation: 117

Regex Matcher Ruby

I am new to the Language.

I am trying to extract all characters till the escape character (\r).

I tried

text = "abcde\r"

text.match(/(.*)(\r)/)

I tried the same with gsub and gsub!. None are working.

Upvotes: 0

Views: 48

Answers (2)

Brian Adkins
Brian Adkins

Reputation: 116

If you happen to be dealing with the specific case of lines from a file, and you want to remove the line ending, you can use chop or chomp. For example:

require 'pp'

lines = [
  "hello",
  "there\r",
  "how\r\n",
  "are you?"
]

lines.each do |line|
  pp line
  pp line.chomp
  puts '---'
end

Results in:

"hello"
"hello"
---
"there\r"
"there"
---
"how\r\n"
"how"
---
"are you?"
"are you?"
---

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176392

You can use String#slice passing the regular expression and the match to get. The 1 represents the first (and in this case the only) match.

text = "abcde\r"
text.slice(/(.*)\r/, 1)
 => "abcde" 

Upvotes: 0

Related Questions