正则表达式 - 组值替换
我不确定这是否可行,但一旦匹配,我需要一种方法来用运行时动态声明的字符串替换正则表达式表达式中指定的编号组的值。
给定一个简单的情况,比如...
(/)?([A-Za-z0-9])?(/)?$
我希望能够插入第 2 组的替代品。
我目前正在使用 Java 的 Matcher 类。
I am not sure if this is possible to do, but I need a way to replace a value of a numbered group specified in the my regex expression with a string declared dynamically at runtime, once a match has been made.
Given a simple case, something like...
(/)?([A-Za-z0-9])?(/)?$
I would want to be able to plugin a replacement for group 2.
I am currently using Java's Matcher class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的。请参阅下面的示例。
此演示“插入”第 2 组的
.toUpperCase
版本作为替代品。印刷:
Yes, it's possible. See the example below.
This demo "plugs in" the
.toUpperCase
version of group 2 as a replacement.Prints:
是的,这是可行的。查看我对这个问题的回答,了解具体方法。事实上,这个问题可能应该作为重复问题来关闭。
您需要稍微更改一下正则表达式。我无法确切地告诉你要做什么,所以我不能给出任何细节,但至少你应该将所有这些问号移到组内。
但它仍然会匹配目标字符串末尾的空子字符串,因为除了锚点
$
之外,所有内容都是可选的。这真的是你想要做的吗?Yes, that's doable. Check out my answer to this question to see how. In fact, this question probably should be closed as a duplicate.
You'll need to change the regex a little. I can't tell exactly what you're trying to do, so I can't give any specifics, but at the very least you should move all those question marks inside the groups.
But it will still match an empty substring at the end of the target string, because everything is optional except the anchor,
$
. Is that really what you meant to do?返回正则表达式搜索的值并将其保存到变量中,然后使用正则表达式搜索结果作为查找目标并使用动态声明的字符串作为替换来对主字符串进行替换。
真正简化的概念:
Return the value of your regex search and save it to a variable, then do a replace on your main string using your regex search results as a find target and your dynamically declared string as a replacement.
Really simplified conceptual: