gpt4 book ai didi

java - 当我们有特定文本到模式时,正则表达式 Java

转载 作者:行者123 更新时间:2023-11-30 02:57:56 25 4
gpt4 key购买 nike

As i haven't much worked on regex, can someone help me out in getting the answer for below thing:

(1)我想删除元素文本

(2)后面可能不跟分隔符,比如管道(||)

I tried below thing, but it is not working in the way i want:

String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
System.out.println(str.replaceFirst("Element.*\\||", ""));
System.out.println(str1.replaceFirst("Element.*\\||", ""));

Required output in above cases:

String:abc||Value:abc //for the first case
String:abc //for the second case

最佳答案

假设您可以决定为原始模式赋予另一个值,在本例中为 Element,您可以使用 Pattern.quote 对其进行转义,如下所示:

String str = "String:abc||Element:abc||Value:abc"; // Sample text 1
String str1 = "String:abc||Element:abc"; // Sample text 2
String originalPattern = "Element";
String pattern = String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern));
System.out.println(str.replaceFirst(pattern, ""));
System.out.println(str1.replaceFirst(pattern, ""));

您的模式是通用的,其值为 String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern))输出:

String:abc||Value:abc
String:abc

关于java - 当我们有特定文本到模式时,正则表达式 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36749799/

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