Saurabh Saurabh - 2 years ago 113
Java Question

Regex Java when we have specific text upto a pattern

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

(1)I want to remove a text say Element

(2)It may of may not followed by delimiter say pipe(||)

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

Answer Source

Assuming that you can decide to give another value to the original pattern which is Element in this case, you can use Pattern.quote to escape it as below:

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, ""));

Your patter is then generic and its value is String.format("\\|{2}%s[^\\|]+", Pattern.quote(originalPattern)) Output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download