【问题标题】:how to replace [10] to {ref10} in java如何在java中将[10]替换为{ref10}
【发布时间】:2017-05-16 19:55:56
【问题描述】:

假设输入是否有任何数字 within[ ] 这是动态的

例如字符串 "the consequent hyperglycemia. [10]" 应该更改为 "the consequent hyperglycemia. {ref10}"

如果会有多个引用来,例如

字符串"with diabetes. [254, 255]" 需要像糖尿病一样改变。 "{ref254}{ref255}"

【问题讨论】:

  • 为了清楚起见,永远不会有多次引用(我认为[10] 就是这样),这样人们就会看到[10,11]?还是一个句子有多个引用?
  • str.replace("[", "{ref").replace("]", "}")?
  • @KevinO 是的,在某些情况下,会有多个引用来,例如患有糖尿病的字符串“。 [254, 255] “需要像糖尿病一样改变。 {ref254}{ref255}”

标签: java regex string replace


【解决方案1】:

你可以使用:

"the consequent hyperglycemia. [10]".replace("[10]", "{ref10}")

编辑

在这种情况下,您可以使用此正则表达式 \[(.*?)\] 替换 [] 之间的所有内容,例如:

String str = "the consequent hyperglycemia. [10]";
String result = str.replaceAll("\\[(.*?)\\]", "{ref$1}");

输出

the consequent hyperglycemia. [10]    -> the consequent hyperglycemia. [ref10]
the consequent hyperglycemia. [99910] -> the consequent hyperglycemia. {ref99910}

编辑 2

在这种情况下,您必须使用 Patterns 例如:

String str = "the consequent hyperglycemia. [10,11][12,13]";

Pattern p = Pattern.compile("\\[.*?\\]");
Matcher m = p.matcher(str);

while (m.find()) {
    str = str.replace(m.group(), m.group().replaceAll("(\\d+)", "{ref$1}")
            .replaceAll("[\\[\\]\\s,]", ""));
}

System.out.println(str);

输出

the consequent hyperglycemia. {ref10}{ref11}{ref12}{ref13}

想法是:

  1. 找到[]之间的所有组
  2. {refInt}替换每个grope的所有int,同时替换所有, and [ and ],结果用它自己的组替换它。

【讨论】:

  • [] 中的值将是动态的
  • @AndyThomas,OP 确实将其放在描述中,但问题标题具有误导性。
  • 现在@KevinO 呢?
  • [10] 的输出示例是否正确?它应该替换为{ref10},非?
  • @pankajdesai 这个信息应该从一开始就在问题中,所以[...] 之间可以有字符串,或者只是用逗号分隔的数字吗?
猜你喜欢
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 2015-01-14
  • 2017-12-10
  • 2020-03-06
  • 2012-09-30
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多