有没有办法使用字符串参数列表和正则表达式(带组)来构造新字符串?
比方说,我有一个像这样的正则表达式:
"The quick (red|brown|blue|yellow) fox (jumps|leaps) over the lazy (dog|cat)."
这个正则表达式有 3 个分组组件 - 如果它与给定的字符串匹配,正则表达式 api 将允许您轻松提取每个组内的值。
现在假设我有 3 个字符串:
["red", "leaps","cat"]
如果我们假设正则表达式中不在组内的所有字符都只是文字文本字符 - 有没有办法将这 3 个字符串中的每一个插入到原始正则表达式中的相应组中,从而产生一个组合了正则表达式的非分组部分的输出字符串?在这种情况下,就产生了“敏捷的红狐狸跳过了懒惰的猫”。 最好不需要有已经与正则表达式匹配的字符串。
我希望在 Java 中做到这一点 - 我很确定 java.util.regex 不支持这一点,但我想也许会有一个第三方库可以实现这一点。有人能给我一些指点吗?
Let's say for example that I have a regular expression like this:
"The quick (red|brown|blue|yellow) fox (jumps|leaps) over the lazy (dog|cat)."
This regex has 3 grouped components - if it's matched against a given string, the regex api would allow you to easily extract the value inside each group.
Now let's say I have 3 strings:
["red", "leaps","cat"]
If we make the assumption that all the characters in the regex that are not inside groups are just literal text characters -
is there a way to then insert each of those 3 strings into the corresponding group in the original regex, resulting in an output string that combines the non-grouped portion of the regex? In this case, resulting in "The quick red fox leaps over the lazy cat."
Preferably, without needing to have a string that has already matched the regex.
I'm looking to do this in Java - I'm quite sure java.util.regex doesn't support this, but I thought maybe there would be a 3rd party lib out there that could allow this to be done. Can anyone give me some pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要您可以不使用嵌套捕获组,您就可以简单地使用更多正则表达式来检索文字:
As long as you can do without nested capturing groups you can simply use more regex to retrieve the literals:
大多数正则表达式实现允许您在搜索和替换中执行类似的操作:
Most regex implementations allow you to do something like this in a search and replace: