有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串java 6 replaceall replacefirst

以下正则表达式在字符串中使用时有效。replaceall(),但不适用于字符串。replaceFirst()

字符串:

TEST|X||Y|Z||

预期产出:

TEST|X|**STR**|Y|Z||

正则表达式:

  string.replaceAll( "(TEST\\|[\\|\\|]*\\\\|)\\|\\|", "$1|ST|" );


Output (not desired):


 TEST|X|**STR**|Y|Z|**STR**|


string.replaceFirst( "(TEST\\|[\\|\\|]*\\\\|)\\|\\|", "$1|ST|" );

不会对字符串进行任何更改

请帮忙

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    如果只想将第一个“| |”替换为“|ST |”,可以执行以下操作:

    System.out.println("TEST|X||Y|Z||".replaceFirst("\\|\\|", "|ST|"));
    
  2. # 2 楼答案

    你的问题不是很清楚,但我想你是在问为什么产出会有差异。在字符串中传递的正则表达式模式有两个匹配项。所以,当你说replace时,所有匹配项都被替换了,当使用replaceFirst时,只替换第一个匹配项。因此,在输出上存在差异。要找到匹配项-

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Regex {
    
        public static void main(String[] args) {
    
            String string1 = new String("TEST|X||Y|Z||");           
    
            Pattern pattern = Pattern.compile("(TEST\\|[\\|\\|]*\\\\|)\\|\\|");
            Matcher matcher = pattern.matcher(string1);
    
            boolean found = false;
            while (matcher.find()) {
                System.out.printf("I found the text \"%s\" starting at "
                        + "index %d and ending at index %d.%n", matcher.group(),
                        matcher.start(), matcher.end());
                found = true;
            }
            if (!found) {
                System.out.printf("No match found.%n");
            }
        }
    }
    
  3. # 3 楼答案

    您的regexp可能没有达到预期效果。原因是管道符号|有两种含义。它是你的seprator,也是regexp中的

    (TEST\\|[\\|\\|]*\\\\|)\\|\\|
    

    您正在有效地搜索测试etc或| |,并且正在匹配这两个| |

    如果您试图只匹配测试后的| | X |,您可以使用

    "(TEST\\|[^\\|]*)\\|\\|"
    

    测试之后是管道,之后是零个或多个非管道,然后是两个管道