I want to remove these patterns in the text:
(22.11.2023): ---> it should be removed
(22.11.2023) : ---> it should be removed
(): ---> it should be removed
() : ---> it should be removed
() ---> it should be removed
(22.11.2023) ---> it should be removed
(text): ---> Should NOT Be Removed
(text) : ---> Should NOT Be Removed
(text) ---> Should NOT Be Removed
Note that our pattern contains:
- two parentheses
- a date between parentheses
- a colon after it
(22.11.2023): oooooo (22.11.2023) : cccc (22.11.2023) aaaaaa () : ddddd () and not remove (text between parentheses)
The above text should return this:
oooooo cccc aaaaaa ddddd and not remove (text between parentheses)
So far I can remove the parenthesis and its containing text like this, but need a hand to fix this
console.log(string.replace(/ *([^)]*) */g, " "))
3
Answers
One way to do this is to make the date and
:
optional:(s*(?:d{2}.d{2}.d{4}s*)?)s*:?
:You can use multiple replacement patterns.
Replacing
(|[0-9.]+):?
with the empty string should do what is required. If the date format is precisely as shown then replace(|dd.dd.dddd):?
. Note that adding extra stuff to validate dates properly (e.g., days per month and months being01
to12
) would make the expression much more complex.Explanation:
The above does not allow for the optional spaces (i.e. the
*
occuring twice) shown in theconsole.Log...
statement.