mardi 6 mai 2014

Java - cocher numéro avec RegEx - Stack Overflow


I tried to write a RegEx


Log.e("before: ", number);
number = number.replaceAll("^[0]{0,4}", "+"); // e.g. 004912345678 -> +4912345678
Log.e("after: ", number);

that makes from


004912345678

+4912345678

and in fact it works, BUT it also makes from


+4912345678

++4912345678

and that I don't want. I don't know why it matches strings, that begin with +, since I wrote ^[0]... in my pattern.




Use ^[0]{1,4} instead of ^[0]{0,4}.


^[0]{0,4} will also accept zero of 0 and as you can see +4912345678 has zero of zeroes so regex will be able to found match and place + there.



I tried to write a RegEx


Log.e("before: ", number);
number = number.replaceAll("^[0]{0,4}", "+"); // e.g. 004912345678 -> +4912345678
Log.e("after: ", number);

that makes from


004912345678

+4912345678

and in fact it works, BUT it also makes from


+4912345678

++4912345678

and that I don't want. I don't know why it matches strings, that begin with +, since I wrote ^[0]... in my pattern.



Use ^[0]{1,4} instead of ^[0]{0,4}.


^[0]{0,4} will also accept zero of 0 and as you can see +4912345678 has zero of zeroes so regex will be able to found match and place + there.


0 commentaires:

Enregistrer un commentaire