How to do lookbehind and lookforward at the same time around a regex?

Viewed 41

The input is this:

*Word. Word.* Word word. *…*

"…" Word word. "…"

"…" word. "…"

The following is matching the empty space on the right side of a sentence.

(?<=["*]*[A-Z].+?\.["*]*)\s

If I want to match the empty space on the left side, I have to do this:

\s(?=["*]*[A-Z].+?\.["*]*)

The output should be this (the [] symbolize the matches):

*Word.[]Word.*[]Word word.[]*…*

"…"[]Woad word.[]"…"

"…" word.[]"…"

How to modify this regex so it matches the empty spaces on both sides of a sentence at the same time?

https://regexr.com/5tddc

2 Answers

For the examples shown, you may be able to use this regex with look arounds to match spaces:

(?<=\.\*?) |(?<!\w) (?=[A-Z])

RegEx Demo

RegEx Details:

  • (?<=\.\*?) : Match a space if that is preceded by a dot and optional *
  • |: OR
  • (?<!\w) (?=[A-Z]): Match a space that must be followed by an uppercase letter and must not be preceded by a word character

Perhaps you can match a non word boundary and assert either an uppercase char A-Z or one of " * at the right.

\B[ ](?=[A-Z"*])

The pattern matches:

  • \B A position where \b does not match
  • [ ] Match a space (The brackets are for clarity only)
  • (?= Positive lookahead, assert what is at the right is
    • [A-Z"*] Match one of A-Z or " or *
  • ) Close lookahead

regex demo

Related