Reputation: 1336
The Regex should identify texts like '0000046qwerty' and replace it with '46qwerty'.
Other Examples:
0000qw --> 0qw
123 --> 123
0123 --> 123
123qw --> 123qw
12003qw --> 12003qw
So, focus is mainly on the leading zeros and a way to truncate them in the appropriate scenario.
Solution I have is: (calls replaceFirst
twice)
text.replaceFirst("^[0]+(\\d+)", "$1").replaceFirst("^[0]*(\\d{1}\\w+)", "$1")
Is there a single line regex to do the operation?
Upvotes: 0
Views: 71
Reputation: 8075
text.replaceFirst("^[0]+(\\d+)", "$1")
works with
0000qw -> 0qw
12003qw -> 12003qw
why do you call the second replaceFirst?
Upvotes: 0
Reputation: 9961
Just "skip" leading zeros, leave one digit and any symbols after it:
text.replaceAll("^0+(\\d.*)", "$1")
Upvotes: 2
Reputation: 2689
Pattern matching is greedy so 0* will match as many zeroes as it can, leaving at least one digit to be matched with \d. ^ means that only leading zeroes will be deleted.
text.replaceAll("^0*(\\d.*)", "$1")
Upvotes: 2
Reputation: 36304
Use regex like this : This works for all your cases :P
public static void main(String[] args) {
String text="0000qw";
System.out.println(text.replaceAll("^0{2,}(?=0[^0])",""));
}
O/P :
0qw
Upvotes: 0