Search code examples
javaregexjedit

Regular expression to wrap matching lines inside pound signs but not leading whitespace


Is there a Regular Expression I could use in the Find/Replace feature of my text editor (Jedit) to do the following:

Match any lines in a text file that meet these criteria:

  1. The line ends with a closing parenthesis
  2. An opening parenthesis exists somewhere on the same line

If it matches I need to wrap all of the text on the line - but not any whitespace at the start of the line- inside # signs.

Example 1

This line:

Total reimbursements (before end of Q1)

needs to be replaced with this:

#Total reimbursements (before end of Q1)#

Example 2 (leading whitespace)

This line (where there is whitespace before the word Total):

                             Total reimbursements (before end of Q1)

needs to be replaced with this (the # sign is placed before the first letter on the line):

                             #Total reimbursements (before end of Q1)#

but NOT with this:

#                             Total reimbursements (before end of Q1)#

Sample text file:

Base Expenses
&&&&&&&&&&&&&&&&&&&&&&&


Provides options towards multilateral improvements

Opening Debt(Option patterns)
          A copy provided externally

Customer Summary
&&&&&&&&&&&&&&&&&&&&&&&&&

 External Console(foreign debt)
          Provide execution amounts
 Internal Console(domestic debt)
          Release to appropriations committee

Explanations provided to external clients

 Neutralized Amounts()
          Forex portion

Solution

  • Regex:

    ^([ \t]*)(.*\(.*\))$

    Replacement:

    $1#$2#

    The trickiest thing is making sure no part of the regex can match newlines. That's why I used [ \t]* instead of \s* and .* instead of [^(]* or [^)]*.