Reputation: 1610
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:
\par
is not followed by d\
, so not \pard\
.\par
is not followed by a \
, so not \par\
.\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
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
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
OR
shorter version would be
(?<=\\par)(?!d?\\|\s)
Upvotes: 4
Reputation: 526
I am a little bit confused by what exactly you want, this?
\\par(?!d\\)(?!\\)(?! ).
Upvotes: 0