Search code examples
regexlookbehind

How to use lookbehind or lookahead and replace the matched string?


I am stuck at one more RegEx.

Sample input :

project description

I want to write RegEx. that if word "description" is found and its preceded by word "project" then prepend "project description" with "<project>".

expected output :

<project>project description

I wrote following Regex, n replacement string but its not working : regex : ((?<=project) description) and replacement string : <project_description>$0

With current regex and replacement string im getting following output :

project<project> description

Can anyone suggest something?


**

EDITED QUESTION

** Ok, I think I am not clear enough about telling people what I want exactly.

To make the problem generic and clearer, I will put it in another way.

If "y" comes after "x", then prepend <tag> to xy.

Is it possible to do this using regular expressions?


Solution

  • EDITED ANSWER:

    This doesn't seem appropriate for lookbehind. Why don't you just replace the whole thing, like this:

    s/(project|other|word) description/<project>$1 description/
    

    This will prepend the word <project> to any of project, other, or word if it is followed by description.