Gregy
Gregy

Reputation: 340

Find and replace special character and special character with character

I would like to to modify given strings:

a = "John;Rich;[email protected]\r\n" 
b = "John;Rich;[email protected]\r" 
c = "John,Rich,[email protected]\n"

To one format:

"xxx,yyy,zzzz\n"

I think the best way to do that is by using regex to find and replace, but I have no experience with it. I wrote simple code to change ; => , :

a.gsub(/[;]/,',')

I figured out that regex /(\\r\\n)/ will find for me \r\n and /(\\r)/ - \r.
I have a problem with joining all regexes together to perform whole string modification with one gsub.

Upvotes: 1

Views: 2470

Answers (4)

Stefan
Stefan

Reputation: 114138

I have a problem with joining all regexes together to perform whole string modification with one gsub.

You can pass a hash to gsub:

replacements = {
  ';'    => ',',
  "\r\n" => "\n",
  "\r"   => "\n"
}

a.gsub(Regexp.union(replacements.keys), replacements)
#=> "John,Rich,[email protected]\n"

b.gsub(Regexp.union(replacements.keys), replacements)
#=> "John,Rich,[email protected]\n"

c.gsub(Regexp.union(replacements.keys), replacements)
#=> "John,Rich,[email protected]\n"

You could also use chomp to remove the line terminators and tr for the substitution:

a.chomp.tr(';', ',') << "\n"
#=> "John,Rich,[email protected]\n"

b.chomp.tr(';', ',') << "\n"
#=> "John,Rich,[email protected]\n"

c.chomp.tr(';', ',') << "\n"
#=> "John,Rich,[email protected]\n"

Upvotes: 3

Taemyr
Taemyr

Reputation: 3437

The pipe character | should solve your problem. foo|bar matches either foo or bar, so you can join your regexps as /(\\r\\n|\\r)/.

However in your case a better solution is ?, (foo)? matches zero or one occurences of foo. So you could write your regexp as /(\\r(\\n)?)/

To do all in a single gsub you need to do replace the whole string in one go. You can do this by;

puts a.gsub(/([^;]*);([^;]*);(.*?)(\r\n|\r|\n)/,"\\1,\\2,\\3\n")

Upvotes: 0

Cylian
Cylian

Reputation: 11182

Try this:

result = subject.gsub(/[\r\n]+/, '\n')

RegEx Anatomy:

"
[\\r\\n]    # Match a single character present in the list below
             # A carriage return character
             # A line feed character
   +         # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
"

Hope this helps...

Upvotes: 4

Toto
Toto

Reputation: 91375

How about:

a.gsub(/\R/,'\n')

\R stands for any line break

Upvotes: 0

Related Questions