当我们将特定文本添加到模式时,正则表达式Java

时间:2016-04-20 16:25:10

标签: java regex

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

3 个答案:

答案 0 :(得分:2)

假设您可以决定为原始模式赋予另一个值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

答案 1 :(得分:0)

你把逃脱错了。它应该是:

Element(.*?\|\||.*$)

将转义放在每个管道上,并使用?作为非贪婪的正则表达式,这样您只能替换足够的字符串,而不是所有内容。

答案 2 :(得分:0)

String text = "String:abc||Element:abc||Value:abc";
text = text.replaceAll("\\belement\\b", "");

你可能需要使用替换所有这将替换你的字符串中的所有元素我在'\b'中使用java regular expression字边界