如何使用lookbehind或lookahead并替换匹配的字符串?
我又陷入了一个正则表达式。
示例输入:
project description
我想编写正则表达式。如果找到单词“description”并且其前面有单词“project”,则在“project description”前面加上“
预期输出:
<project>project description
我编写了以下正则表达式,n 替换字符串,但它不起作用: 正则表达式:((?<=项目)描述)
和替换字符串:
使用当前的正则表达式和替换字符串,我得到以下输出:
project<project> description
任何人都可以提出建议吗?
**
编辑问题
** 好吧,我想我还不够清楚地告诉人们我到底想要什么。
为了使问题更通用、更清晰,我会用另一种方式来表达。
如果“y”位于“x”之后,则在 xy 前面添加
。
是否可以使用正则表达式来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白为什么你要使用lookbehind - 你可以这样做:
在 PHP 中,这将是
I don't understand why you're using a lookbehind for this - you can just do:
In PHP this would be
扩展 Greg 的正则表达式以匹配新添加的案例:
您稍后可以使用
|
将新案例添加到此正则表达式。编辑:要回答
如果“y”出现在“x”之后,则在前面添加;到 xy。
这会将
前置到所有出现的 x-space- yExtending Greg's regex to match the newly added cases:
You can later add new cases to this regex using
|
.EDIT: To answer
If "y" comes after "x", then prepend <tag> to xy.
This will prepent
<tag>
to all occurrences of x-space-y编辑答案:
这似乎不适合向后查找。为什么不直接替换整个内容,如下所示:
这会将
一词添加到project
、other
中的任何一个前面,或word
(如果后跟description
)。EDITED ANSWER:
This doesn't seem appropriate for lookbehind. Why don't you just replace the whole thing, like this:
This will prepend the word
<project>
to any ofproject
,other
, orword
if it is followed bydescription
.