Java 正则表达式多模式组替换 [英] Java Regex Multiple Pattern Group Replace

查看:58
本文介绍了Java 正则表达式多模式组替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串

String Context = "old1 old2 old3 old4 old5 old6"

我想做一个模式:(old2).*(old4)

所以单词 2 将在 $1 中,而 word4 将在 $2 中.

so word 2 would be in $1 and word4 would be in $2.

有什么函数或方法可以同时替换两个单词的字符串吗?仅使用组变量($1$2)?

Is there any functions or methods that i can replace the two words strings at the same time? Using only the group variable ($1 and $2) ?

所以我可以指定 $1 将成为 new2$2 将成为 new4.我不想找到字符串 old2old4 并将其替换为 new2new4

So I could specify that $1 will become new2 and $2 will become new4. I don't want to have to find the string old2 and old4 and replace it to new2 and new4

推荐答案

只需要一组

如果我理解,这就是您所需要的:

If I am understanding, this is what you need:

String replaced = yourString.replaceAll("old2(.*?)old4", "new2$1new4");

说明

  • old2 匹配文字字符
  • (.*?) 懒惰地匹配字符(将它们捕获到组 1),最多...
  • old4
  • new2替换Group 1和new4的内容
  • old2 matches literal chars
  • (.*?) lazily matches chars (capturing them to Group 1), up to...
  • old4
  • Replace with new2, the content of Group 1 and new4

这篇关于Java 正则表达式多模式组替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆