in r and regex, how to detect a character with excluding some mixed condition

Viewed 49

I'm trying to detect some dots (.) in my string and replace them with the same dots alongside a word, for example "." becomes ".AAA" . but there are some conditions that I want to avoid replacing:

  1. if there is a space and then a single character before the dot
  2. if the dots are between two hyphens (-)

for example, if the input is:

string <- "first. - second. - third. 4."

my desired output is:

"first.AAA - second. - third.AAA 4."

for the first condition I could figure out this:

str_replace_all("[^ [A-Z19a-z]\\.]([\\.])","\\1AAA")

but got confused when reading about look-ahead and look-behind for solving the second condition and mixing the two together.

1 Answers

If by a single character you mean any char including line break chars, you can use

gsub("(?s)(?:\\s.\\.|-[^-]*-)(*SKIP)(?!)|(\\.)", "\\1AAA", x, perl=TRUE)

See the regex demo. If you need to precise that "any char" condition replace the unescaped dot in \\s.\\. with the appropriate construct.

Details:

  • (?s) - a dotall s flag that makes the dot match any chars incluing line break chars
  • (?:\s.\.|-[^-]*-) - a non-capturing group matching either
    • \s.\. - a whitespace, any one char, a dot
    • | - or
    • -[^-]*- - a hyphen, zero or more chars other than a hyphen and then a hyphen
  • (*SKIP)(?!) - skip the match failing it at the current location and triggering the search for the next match from the failure position
  • | - or
  • (\.) - Group 1: a dot.
Related