Try this:
^\d{5}\s{6}[\s\*] # Your original pattern
(?: # Repeat 0 or more times:
[^.:;()]*| # Unconstrained characters
(?<!\s)[.:;](?=\s)| # Punctuation after non-space, followed by space
\((?!\s)| # Opening parentheses not followed by space
(?<!\s)\) # Closing parentheses not preceeded by space
)*
\.$ # Period, then end of string
https://regex101.com/r/WwpssV/1
In the last part of the pattern, the characters with special requirements are .:;()
, so use a negative character set to match anything but those characters: [^.:;()]*
Then alternate with:
if there is any period, colon or semicolon before the final period, the character must not be preceded by a white space, but it must be followed by a white space.
Fulfilled by (?<!\s)[.:;](?=\s)
– match one of those characters only if not preceded by a space, and if followed by a space.
opening parentheses cannot be followed by a white space.
Fulfilled by \((?!\s)
closing parentheses cannot be preceded by a white space.
Fulfilled by (?<!\s)\)
Then just alternate between those 4 possibilities at the end of the pattern.
CLICK HERE to find out more related problems solutions.