<分区>
当我在下面尝试这段代码时,它使用正则表达式边界工作正常:
"word john word".replaceAll("\\bjohn\\b","fill")
Result: "word fill word"
但是如果我需要搜索一个包含“#”的单词,它就不起作用了:
"word john# word".replaceAll("\\john#\\b","fill")
Result: "word john# word"
我该如何解决?
<分区>
当我在下面尝试这段代码时,它使用正则表达式边界工作正常:
"word john word".replaceAll("\\bjohn\\b","fill")
Result: "word fill word"
但是如果我需要搜索一个包含“#”的单词,它就不起作用了:
"word john# word".replaceAll("\\john#\\b","fill")
Result: "word john# word"
我该如何解决?
最佳答案
她 #
符号不计为单词字符 ([A-Za-z0-9_]
),所以你的单词边界 (\b
) 不再匹配。
您可以使用正向前瞻并以空白为基础:
"word john# word".replaceAll("\\bjohn#(?=\\s+)","fill") // word fill word
或者使用非词边界(\B
):
"word john# word".replaceAll("\\bjohn#\\B","fill") // word fill word
或者什么都没有:
"word john# word".replaceAll("\\bjohn#","fill") // word fill word
关于java - 为什么当我添加尖锐信号时,Java ReplaceAll with Regex 边界不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659219/
相关文章:
javascript - 正则表达式检查具有一系列模式的数字
javascript - 如何为不确定长度的参数形成 JavaScript 正则表达式
java - Collection.stream() 是否有内部同步?
android-支持库 BottomNavigationView 不显示标题
android - 在我的应用程序中创建一个模拟的 Android 环境
java - Android xml和Java : Get text from Edit Text,找不到符号错误
java - 当我从另一 Activity 获取结果时,ListView 仅更新一个 View 项,如何获取所有过去的结果?