How do i remove empty lines from a string?
I have tried
some_string = some_string.gsub(/^$/, "");
and much more, but nothing works.
Remove blank lines:
str.gsub /^$\n/, ''
Note: unlike some of the other solutions, this one actually removes blank lines and not line breaks :)
>> a = "a\n\nb\n"
=> "a\n\nb\n"
>> a.gsub /^$\n/, ''
=> "a\nb\n"
Explanation: matches the start ^ and end $ of a line with nothing in between, followed by a line break.
Alternative, more explicit (though less elegant) solution:
str.each_line.reject{|x| x.strip == ""}.join
squeeze (or squeeze!) does just that - without a regex.
str.squeeze("\n")
Replace multiple newlines with a single one:
fixedstr = str.gsub(/\n\n+/, "\n")
or
str.gsub!(/\n\n+/, "\n")
You could try to replace all occurrences of 2 or more line breaks with just one:
my_string.gsub(/\n{2,}/, '\n')
Originally
some_string = some_string.gsub(/\n/,'')
Updated
some_string = some_string.gsub(/^$\n/,'')
Related
Starting with this string:
file = "[/my/directory/file-*.log]"
I want to remove anything that comes after the trailing / and the closing square bracket, so the returned string is:
file = "[/my/directory/]"
I wondered if someone could recommend the safest way to do this.
I have been experimenting with chomp but I’m not getting anywhere, and gsub or sub doesn’t seem to fit either.
You can use File.dirname:
File.dirname("/my/directory/file-*.log")
=> "/my/directory"
If it's stuck inside the brackets, you can always write a custom replacement function that calls out to File.dirname:
def squaredir(file)
file.sub(/\[([^]]+)\]/) do |m|
'[%s]' % File.dirname($1)
end
end
Then you get this:
squaredir("[/my/directory/file-*.log]")
# => "[/my/directory]"
Here are three non-regex solutions:
file[0..file.rindex('/')] << ']'
file.sub(file[file.rindex('/')+1..-2], '')
"[#{File.dirname(file[1..-2])}]"
All return "[/my/directory/]".
file.split('/').take(file.split('/').size - 1).join('/') + ']'
=> "[/my/directory]"
Split the string into an array of strings separated by /
Take all the array elements except the last element
Join the strings together, re-inserting / between them
Add a trailing ]
file = "[/my/directory/file-*.log]"
file.sub(/^(.+)\/([^\/]+)\]/, '\1/]')
=> "[/my/directory/]"
I want to write a regex in Ruby that will add a backslash prior to any open square brackets.
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
# desired out = "my.name\[0].hello.line\[2]"
I've tried multiple combinations of backslashes in the substitution string and can't get it to leave a single backslash.
You don't need a regular expression here.
str = "my.name[0].hello.line[2]"
puts str.gsub('[', '\[')
# my.name\[0].hello.line\[2]
I tried your code and it worked correct:
str = "my.name[0].hello.line[2]"
out = str.gsub(/\[/,"\\[")
puts out #my.name\[0].hello.line\[2]
If you replace putswith p you get the inspect-version of the string:
p out #"my.name\\[0].hello.line\\[2]"
Please see the " and the masked \. Maybe you saw this result.
As Daniel already answered: You can also define the string with ' and don't need to mask the values.
Is it possible to display the characters around a regex match? I have the string below, and I want to substitute every occurrence of "change" while displaying the 3-5 characters before the match.
string = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"
What I have so far
while line.match(/change/)
printf "\n\n Substitute the FIRST change below:\n"
printf "#{line}\n"
printf "\n\tSubstitute => "
substitution = gets.chomp
line = line.sub(/change/, "#{substitution}")
end
If you want to get down and dirty Perl style:
before_chars = $`[-3, 3]
This is the last three characters just before your pattern match.
You would likely use gsub! with block given in the following manner:
line = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"
# line.gsub!(/(?<where>.{0,3})change/) {
line.gsub!(/(?<where>\S+)change/) {
printf "\n\n Substitute the change around #{Regexp.last_match[:where]} => \n"
substitution = gets.chomp
"#{Regexp.last_match[:where]}#{substitution}"
}
puts line
Yielding:
Substitute the change around val= =>
111
Substitute the change around anotherval= =>
222
Substitute the change around stringhere: =>
333
val=111 anotherval=222 stringhere:333: foo=bar foofoo=barbar
gsub! will substitute the matches in place, while more suitable pattern \S+ instead of commented out .{0,3} will give you an ability to print out the human-readable hint.
Alternative: Use $1 Match Variable
tadman's answer uses the special prematch variable ($`). Ruby will also store a capture group in a numbered variable, which is probably just as magical but possibly more intuitive. For example:
string = "val=change anotherval=change stringhere:change: foo=bar foofoo=barbar"
string.sub(/(.{3})?change/, "\\1#{substitution}")
$1
# => "al="
No matter what method you use, though, make sure you explicitly check your match variables for nils in the event that your last attempted match was unsuccessful.
Given the following indented text:
two spaces
four
six
non-leading spaces
I'd like to convert every 2 leading spaces to a tab, essentially converting from soft tabs to hard tabs. I'm looking for the following result (using an 'x' instead of "\t"):
xtwo spaces
xxfour
xxxsix
non-leading spaces
What is the most efficient or eloquent way to do this in ruby?
What I have so far seems to be working, but it doesn't feel right.
input.gsub!(/^ {2}/,"x")
res = []
input.split(/\n/).each do |line|
while line =~ /^x+ {2}/
line.gsub!(/^(x+) {2}/,"\\1x")
end
res << line
end
puts res.join("\n")
I noticed the answer using sed and \G:
perl -pe '1 while s/\G {2}/\t/gc' input.txt >output.txt
But I can't figure out how to mimic the pattern in Ruby. This is as far as I got:
rep = 1
while input =~ /^x* {2}/ && rep < 10
input.gsub!(/\G {2}/,"x")
rep += 1
end
puts input
Whats wrong with using (?:^ {2})|\G {2} in multi-line mode?
The first match will always be at the beginning of the line,
then \G will match succesively right next to that, or the match
will fail. The next match will always be the beginning of the line.. repeats.
In Perl its $str =~ s/(?:^ {2})|\G {2}/x/mg; or $str =~ s/(?:^ {2})|\G {2}/\t/mg;
Ruby http://ideone.com/oZ4Os
input.gsub!(/(?:^ {2})|\G {2}/m,"x")
Edit: Of course the anchors can be factored out and put into an alternation
http://ideone.com/1oDOJ
input.gsub!(/(?:^|\G) {2}/m,"x")
You can just use a single gsub for that:
str.gsub(/^( {2})+/) { |spaces| "\t" * (spaces.length / 2) }
I have a string of four blank lines which all up makes eight lines in total in the following:
str = "aaa\n\n\nbbb\n\nccc\ddd\n"
I want to return this all in one line. The output should be like this on a single line:
aaabbbcccddd
I used various trim functions to get the output but still I am failing.
What method do I have to use here?
The Ruby (and slightly less Perl-ish) way:
new_str = str.delete "\n"
...or if you want to do it in-place:
str.delete! "\n"
str.gsub(/\n/,'')
> str = "aaa\n\n\nbbb\n\nccc\ddd\n"
=> "aaa\n\n\nbbb\n\ncccddd\n"
> str.gsub("\n", "")
=> "aaabbbcccddd"