0

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?

asked Mar 6, 2015 at 12:49
5
  • 0000qw --> 0qw seems not to be consistent with the other examples. Is there another rule that must hold? Commented Mar 6, 2015 at 13:03
  • @StefanA No. Nothing else I could identify from the data. Commented Mar 6, 2015 at 13:15
  • Don't you see that this rule does leave a 0 behind? Are not all zeros stripped - or is it a wrong example? Or is it a 'O'? Commented Mar 6, 2015 at 13:17
  • @StefanA : Yes, not all the zeros are stripped. It depends upon the successive value. If it is an alphabet then preserve a single zero else discard them. Commented Mar 6, 2015 at 13:21
  • so what was wrong with text.replaceFirst("^[0]+(\\d+)", "1ドル") without the second call to replaceFirst. The second call seems to do nothing. Commented Mar 6, 2015 at 13:30

4 Answers 4

2

Just "skip" leading zeros, leave one digit and any symbols after it:

text.replaceAll("^0+(\\d.*)", "1ドル")
answered Mar 6, 2015 at 12:56
Sign up to request clarification or add additional context in comments.

4 Comments

Ya.. Didn't think like you did.. +1 :P
@StefanA - fixed. Add ^
But Neil was first ;)
Just still my idea and improve it :D
2

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ドル")
answered Mar 6, 2015 at 13:00

Comments

0

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
answered Mar 6, 2015 at 12:53

Comments

0
text.replaceFirst("^[0]+(\\d+)", "1ドル")

works with

0000qw -> 0qw
12003qw -> 12003qw

why do you call the second replaceFirst?

answered Mar 6, 2015 at 13:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.