Richard
Richard

Reputation: 6116

Regex selecting line by search for word in between

I have text like this:

something text
(some text here image and more text)
some more text
(test)
text

I want to do a regex search for everything in between the 2 parenthesis and search for the word image, if that word exists between 2 parenthesis then I want to add a new line AFTER that line. So my regex should produce this output:

something text
(some text here image and more text)

some more text
(test)
text

How can I best achieve this? I've tried (?<=\()(?=image)(?=\)) but that didn't work.

Upvotes: 1

Views: 50

Answers (3)

m87
m87

Reputation: 4523

You can use the following regex to search for the word image in between parentheses and by replacing it with the captured group and a new line you can get the expected result :

(\(.*?image.*?\))

­

input        >>  something text
                 (some text here image and more text)
                 some more text
                 (test)
                 text
regex search >>  (\(.*?image.*?\))
replace with >>  `$1\n`
output       >>  something text
                 (some text here image and more text)

                 some more text
                 (test)
                 text

see demo / explanation

Upvotes: 1

M A
M A

Reputation: 72854

Using a word boundary:

\(.*\bimage\b.*\)

To capture that pattern when matching, place it within parentheses:

(\(.*\bimage\b.*\))

Then try referencing the group using $1 (or \1 depending on the language in which the regex is being used).

Upvotes: 1

karakfa
karakfa

Reputation: 67507

you didn't mention a tool, but with sed

sed 's/(.*image.*)/&\n/' file

if you want to restrict to standalone word "image" use \b word boundary (I think GNU sed only though)

sed 's/(.*\bimage\b.*)/&\n/' file

Upvotes: 1

Related Questions