n_x_l
n_x_l

Reputation: 1610

Ruby Regex: Insert space if set of characters encountered

I would like your help formulating a regex in Ruby.

I would like to insert a space after the literal \par in a string only if these conditions are met:

  1. \par is not followed by d\, so not \pard\.
  2. \par is not followed by a \, so not \par\.
  3. And \par should not be followed by space, so not \par.

Here is what I came up with:

my_string.gsub!(/(?<=\\par).(?!(\d\\)|(\S)|(\\))/, ' '), but this does not work for me at the moment.

Any ideas?

Upvotes: 1

Views: 52

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

This is another way, which only uses a negative lookahead:

def stuff_space_maybe(s)
  s.gsub(/\\par(?!\s|d?\\)/,'\par ')
end

stuff_space_maybe("let's \\part\\y!")
  #=> "let's \\par t\\y!" 
stuff_space_maybe("let's \\pard\\y!")
  #=> "let's \\pard\\y!" 
stuff_space_maybe("let's \\par\\y!")
  #=> "let's \\par\\y!" 
stuff_space_maybe("let's \\par\\ty!")
  #=> "let's \\par\\ty!" 

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

You were close. Try changing the regex as

(?<=\\par)(?!d\\|\s|\\)

Changes made

  • Drop the . between the look arounds. This is required as the . would be matched and consumed by engine

  • \d to d as you intend to match d and not digits (\d)

  • \S to s You have already used a negative look ahead. so \s with the negation ensurs that there is no space following \par

Rubular Demo

OR

shorter version would be

(?<=\\par)(?!d?\\|\s)

Upvotes: 4

AMDcze
AMDcze

Reputation: 526

I am a little bit confused by what exactly you want, this?

\\par(?!d\\)(?!\\)(?! ).

Upvotes: 0

Related Questions