gpt4 book ai didi

java - 例如,我如何区分 hello1 和 hello 11?

转载 作者:行者123 更新时间:2023-11-30 03:47:36 25 4
gpt4 key购买 nike

我正在使用 java 编程,我需要替换 String 中的某些关键字。

假设我的字符串是 "Int hello1\n Int hello11​​" 并且我想将 "hello1" 替换为 "a" 并且“hello11​​” 代表 “b”

问题是当我说 String.replaceAll("hello1", "a"); 时,原始字符串保持这样的状态:Int a\n Int a1,如何防止替换hello11​​

我应该使用什么正则表达式?

最佳答案

您可以为此使用单词边界。

您还需要将 replaceAll 调用创建的 String 分配给另一个变量,因为 Java String 是不可变的。

在此示例中,我只是通过标准输出流打印它。

String input = "Int hello1 \n Int hello11";
System.out.println(input.replaceAll("\\bhello1\\b", "a"));

输出

Int a 
Int hello11

关于java - 例如,我如何区分 hello1 和 hello 11?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25240988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com