perl 模式一一匹配并处理
我有一个字符串,
[something]text1[/something] blah blah [something]text2[/something]
我需要编写一个 Perl 脚本来读取 [something]
标记中的内容,将其处理为“text-x”,然后用 [otherthing] 将其放回
标签。所以上面的字符串应该是
[otherthing]text-1[/otherthing] blah blah [otherthing]text-2[/otherthing]
处理“textx”到“text-x”不是一步过程。
所以这是我到目前为止所拥有的解决方案:
m/[something](?<text>.*)[/something]/
这将为我提供中间的字符串,我可以将其处理为“text-x”,但如何将其放回与 [otherthing]text-x 相同的位置[/其他]
?
- 在这种情况下我该如何使用 s/// ?
- 如何将整个字符串一一处理?
I have a string
[something]text1[/something] blah blah [something]text2[/something]
I need to write a Perl script to read what is in the [something]
tag, process it to "text-x", and put it back with an [otherthing]
tag. So the above string should be
[otherthing]text-1[/otherthing] blah blah [otherthing]text-2[/otherthing]
Processing "textx" to "text-x" is not one step process.
So this is solution that I have till now:
m/[something](?<text>.*)[/something]/
This will get me the string in between and I can process that to "text-x" but how do I put it back in the same place with [otherthing]text-x[/otherthing]
?
- How do I use s/// in this case?
- How to do it for the whole string one by one ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
s///
上的/e
开关来计算右侧,然后再使用结果作为替换,并且/g
> 标记为每场比赛执行此操作。这是一个简单的例子:
You can use the
/e
switch ons///
to evaluate the right hand side before using the result as the substitution, and the/g
flag to do this for every match.Here is a simple example:
这应该很接近。它使用 /e 修饰符允许您在正则表达式的替换端进行处理,因此它调用 fix_textx 函数,您可以在其中执行多个步骤。
迭代匹配的正常方法是使用 /g 修饰符。
编辑:修复了方括号。谢谢@tadmc
This should come close. It uses the /e modifier to allow you to do processing in the replacement side of the regex and so it calls the fix_textx function where you can do multiple steps.
The normal way of iterating over matches is with the /g modifier.
EDIT: fixed the square bracket. Thanks @tadmc
在这种特殊情况下,您可以通过拆分
"[something]"
上的字符串,然后处理每个部分的开头(第一个部分除外),然后加入完成后将碎片重新组合在一起。我不知道是否有通用的方法来迭代 Perl 中字符串中的正则表达式匹配。我希望其他人能回答这个问题并教育我。
In this particular case, you can accomplish what you're trying to do by splitting the string on
"[something]"
and then processing the beginning of each piece (except the first one), then joining the pieces back together when you're done.I don't know if there is a general way to iterate over the regex matches in a string in Perl. I'm hoping someone else will answer this question and educate me on that.