skip to Main Content

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


  1. One way to do this is to make the date and : optional: (s*(?:d{2}.d{2}.d{4}s*)?)s*:?:

    const string = `(22.11.2023): oooooo (22.11.2023) aaaaaa () and not remove (text between parenthesis)`;
    console.log(string.replace(/(s*(?:d{2}.d{2}.d{4}s*)?)s*:?/g, ""));
    Login or Signup to reply.
  2. You can use multiple replacement patterns.

    const process = (text) => text
      .replace(/()[ ]?(:[ ])?/g, '') // Empty parens
      .replace(/(d{2}.d{2}.d{4})[ ]?(:[ ])?/g, '') // Paren-wrapped dates
      .replace(/[ ][ ]+/g, ' '); // Consolidate multiple space sequences
    
    const input = '(22.11.2023): oooooo (22.11.2023) aaaaaa () and not remove (text between parenthesis)';
    const expected = 'oooooo aaaaaa and not remove (text between parenthesis)';
    const actual = process(input);
    
    console.log(actual === expected);
    Login or Signup to reply.
  3. 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 being 01 to 12) would make the expression much more complex.

    Explanation:

    (                 The opening bracket
                       (nothing)
     |                 Or
       [0-9.]+         One or more of a digit or a full stop
    )                 The closing bracket
    :?                 Optional colon
    

    The above does not allow for the optional spaces (i.e. the * occuring twice) shown in the console.Log... statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search