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?
4 Answers 4
Just "skip" leading zeros, leave one digit and any symbols after it:
text.replaceAll("^0+(\\d.*)", "1ドル")
4 Comments
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ドル")
Comments
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
Comments
text.replaceFirst("^[0]+(\\d+)", "1ドル")
works with
0000qw -> 0qw
12003qw -> 12003qw
why do you call the second replaceFirst?
0behind? Are not all zeros stripped - or is it a wrong example? Or is it a 'O'?text.replaceFirst("^[0]+(\\d+)", "1ドル")without the second call to replaceFirst. The second call seems to do nothing.