英文:
Replace .(dot) inside number Java between two elements
问题
我有这个字符串:
String str = "<p>23.5</p>";
我想仅在<p>元素内部将点替换为逗号。我需要的输出是:
<p>23,5</p>
我无法弄清楚,我有以下代码:
str = str.replaceAll(""(?<=<p>)\\.(?=</p>)"", "","");
但它不起作用。我需要仅在特定标签(这是一个字符串中的 XML)的元素中替换点,这里是<p>。
谢谢
英文:
I have this String:
String str = "<p>23.5</p>";
And i want to replace the dot for comma only inside <p> elements. The output i need is:
<p>23,5</p>
I cant figure it out, i have this:
str = str.replaceAll("(?<=<p>)\\.(?=</p>)", ",");
But it doesnt work. I need to replace dot only in elements with particular tag (is an xml in a String), in this case <p>.
Thank you
答案1
得分: 1
你可以使用捕获组+转义斜杠:
str = str.replaceAll("(?<=<p>)(\\d*)\\.(\\d+)(?=<\\/p>)", "$1,$2");
如果你想要替换所有数字中的点号,同样可以使用:
str = str.replaceAll("(\\d*)\\.(\\d+)", "$1,$2");
英文:
You may use capturing groups + escape the /
:
str = str.replaceAll("(?<=<p>)(\\d*)\\.(\\d+)(?=<\\/p>)", "$1,$2");
If you want to replace dot in all numbers, you may just as well use
str = str.replaceAll("(\\d*)\\.(\\d+)", "$1,$2");
答案2
得分: 1
以下是您要求的翻译内容:
以下正则表达式将匹配位于数字字符之间的点字符:
(?<=\d)\.(?=\d)
正则表达式解释:
\d
- 匹配任何 0-9 之间的数字(?<=\d)\.
- 正向后查找,匹配在点号之前有一个数字的任何点号字符\.(?=\d)
- 正向前查找,匹配在点号之后有一个数字的任何点号字符
演示:
https://regex101.com/r/WMEjPl/1
Java 代码示例:
public static void main(String args[]) {
String regex = "(?<=\\d)\\.(?=\\d)";
String str = "<p>23.5</p>";
String str2 = "Mr. John <p>23.5</p> Hello";
String str3 = "Mr. John <p>23.5</p> Hello 12.2324";
System.out.println(str.replaceAll(regex, ",")); // <p>23,5</p>
System.out.println(str2.replaceAll(regex, ",")); // Mr. John <p>23,5</p> Hello
System.out.println(str3.replaceAll(regex, ",")); // Mr. John <p>23,5</p> Hello 12,2324
}
英文:
Following regex will match the dot character that is between numerical characters
(?<=\d)\.(?=\d)
Regex Explanation:
\d
- match any digit between 0-9(?<=\d)\.
- positive look-behind to match any.
character that has a digit just before it\.(?=\d)
- positive look-ahead to match any.
character that has a digit just after it
Demo:
https://regex101.com/r/WMEjPl/1
Java Code Example:
public static void main(String args[]) {
String regex = "(?<=\\d)\\.(?=\\d)";
String str = "<p>23.5</p>";
String str2 = "Mr. John <p>23.5</p> Hello";
String str3 = "Mr. John <p>23.5</p> Hello 12.2324";
System.out.println(str.replaceAll(regex, ",")); // <p>23,5</p>
System.out.println(str2.replaceAll(regex, ",")); // Mr. John <p>23,5</p> Hello
System.out.println(str3.replaceAll(regex, ",")); // Mr. John <p>23,5</p> Hello 12,2324
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论