EN
Java - remove prefix from string
0 points
In this article, we would like to show you how to remove prefix from string in Java.
Quick solution:
xxxxxxxxxx
1
String text = "ABCD";
2
3
// replace "AB" only if it is at the beginning
4
String result1 = text.replaceAll("^AB","");
5
6
// remove the first two characters
7
String result2 = text.substring(2);
8
9
10
System.out.println(result1); // CD
11
System.out.println(result2); // CD
In this example, we use replaceAll()
method with regex to replace the first two letters (AB
) with an empty string.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
6
// replace the AB only at the beginning of the string
7
String result = text.replaceAll("^AB", "");
8
9
System.out.println(result); // CD
10
}
11
}
In this example, we use substring()
method to remove first two letters from the text
.
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
String text = "ABCD";
5
6
// remove the first two characters
7
String result = text.substring(2);
8
9
System.out.println(result); // CD
10
}
11
}