开发者

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 : reg开发者_开发知识库ex : ((?<=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?


I don't understand why you're using a lookbehind for this - you can just do:

/project description/  ->  <project>$0

In PHP this would be

echo preg_replace('/project description/', '<project>$0', $str);


Extending Greg's regex to match the newly added cases:

/Details\sof\sproject|project(\sdescription|s\sundertaken|\(s\)\ssummary)/

//replace all the matches with

<project>$0

You can later add new cases to this regex using |.


EDIT: To answer If "y" comes after "x", then prepend <tag> to xy.

Replace /x\s\y/ with <tag>$0

This will prepent <tag> to all occurrences of x-space-y


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜