"first name" "code_numbers = '123_456'" => "code-6ren">
gpt4 book ai didi

java - 替换撇号之间的所有下划线(Java,字符串)

转载 作者:行者123 更新时间:2023-11-30 06:22:37 25 4
gpt4 key购买 nike

我需要替换字符串中的所有下划线,除了落在两个撇号范围内的下划线。例如:

"first_name" => "first name"
"code_numbers = '123_456'" => "code numbers = '123_456'"

我目前只是使用 .replaceAll("_", "") 丢弃所有下划线,因为它们不是很常见,但我现在想触及所有底线以防万一。

最佳答案

这应该有效(此正则表达式替换了所有 _ 后跟偶数个单引号)。当然,这需要你的报价是平衡的:

String str = "\"code_numbers = '123_456'\"";

str = str.replaceAll("(?x) " +
"_ " + // Replace _
"(?= " + // Followed by
" (?: " + // Start a non-capture group
" [^']* " + // 0 or more non-single quote characters
" ' " + // 1 single quote
" [^']* " + // 0 or more non-single quote characters
" ' " + // 1 single quote
" )* " + // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
" [^']* " + // Finally 0 or more non-single quotes
" $ " + // Till the end (This is necessary, else every _ will satisfy the condition)
") " , // End look-ahead
""); // Replace with ""

关于java - 替换撇号之间的所有下划线(Java,字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19082473/

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