0

I am looking for pattern where I am looking to replace string within (), []. And this has to be done in the start and end of the string.

I use this pattern.

\([^)]*\)

And this replace strings everywhere

Eg.

 Original                                 Expected
Start 1306 Sewing Machine (White) --  Singer Start 1306 Sewing Machine
(White) Start 1306 Sewing Machine --  Singer Start 1306 Sewing Machine
Start 1306 Sewing Machine [White] --  Singer Start 1306 Sewing Machine
[White] Start 1306 Sewing Machine --  Singer Start 1306 Sewing Machine
1
  • You mention the "end" of the string, but your example text technically does not have any () or [] at the end of either each line nor the end of the entire string. Are you considering the "end" before the "--"? The example text seems incomplete to me. Perhaps update the example text to include all possible example of what you want to match and those that you do not want to match. Commented Jul 29, 2017 at 14:37

2 Answers 2

1

I guess, "--" means "original -- edited"...

You have to use ^ (start of line) and $ (end of line) like this:

(^\([^)]*\)|\[[^]]*\])|(\([^)]*\)|\[[^]]*\]$)

For clarity:

( ... )|( ... ) Alternation - match 1st () OR 2nd () ^ start of line, followed by

\([^)]*\)|\[[^]]*\] (anything that is not ")") or [anything that is not "]"]

| OR

\([^)]*\)|\[[^]]*\] (anything that is not ")") or [anything that is not "]"] followed by

$ end of line

Note that ^ has more than one meaning here - start of line and inversion for character class.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Looks like I am missing something. No matches found regex101.com/r/kQ2jS3/11
Sorry, put the braces for the outer alternation into the wrong place while writing. They have to be around the ^/$ as well.
0

This works

Find (?m)^(?:(?:\([^()]*\)|\[[^\[\]]*\])\s*(.*?)\s*(?:\([^()]*\)|\[[^\[\]]*\])?\s*|\s*(.*?)\s*(?:\([^()]*\)|\[[^\[\]]*\])\s*)$

Replace Singer $1$2

https://regex101.com/r/wG0rvD/1

Expanded

 (?m)
 ^ 
 (?:
      (?:
           \( [^()]* \)
        |  
           \[ [^\[\]]* \]
      )
      \s*       
      ( .*? )                       # (1)
      \s* 
      (?:
           \( [^()]* \)
        |  
           \[ [^\[\]]* \]
      )?
      \s* 
   |  
      \s*       
      ( .*? )                       # (2)
      \s* 
      (?:
           \( [^()]* \)
        |  
           \[ [^\[\]]* \]
      )
      \s* 
 )
 $     

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.