简体   繁体   English

删除字符出现直到第一个不同的字符,Java

[英]Remove Character Occurrences Until the First Different One, Java

So I have some numerical strings like the following ones:所以我有一些数字字符串,如下所示:

"00000545468" - "00002021" - "000000001990" etc.. (I don't know how this strings will be passed to me, the only thing I know is that they will start with some zeros from left and then there will be other different numbers) “00000545468”-“00002021”-“000000001990”等。(我不知道这些字符串将如何传递给我,我唯一知道的是它们将从左边的一些零开始,然后会有其他不同的数字)

I want to remove all the zeros (0) occurrences from left until the first different number of the string.我想从左边删除所有出现的零 (0) 直到字符串的第一个不同数字。 So if I have for example "00002021", I want to have as a result "2021" and if I have "000000001990" I want "1990".因此,如果我有例如“00002021”,我希望结果是“2021”,如果我有“000000001990”,我想要“1990”。

I excluded the usage of .replace("0", "") , because by doing this I would also remove the zero in "2021" and in "1990", and I don't want this to happen.我排除了.replace("0", "")的使用,因为这样做我也会删除“2021”和“1990”中的零,我不希望这种情况发生。

Any suggestions?有什么建议么?

You can use the replaceFirst method of String which takes a regex as its first argument to archieve that.您可以使用 String 的replaceFirst方法,该方法将正则表达式作为其第一个参数来存档。

eg:例如:

System.out.println("00002021".replaceFirst("0+", ""));

will print将打印

2021

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用Java中的不同字符替换一个字符的多次出现 - Replace multiple occurrences of one character with different characters in Java 从字符串的开头删除出现的 X 字符,直到在 Java 中找不到不同的字符 - Remove X Character occurence from Starting of string until Different Character Not found in Java 子串化字符串直到Java中的第一个数字字符 - Substring a string until first number character in Java 使用Java Regex删除字符串开头的给定字符序列的出现次数 - Remove occurrences of a given character sequence at the beginning of a string using Java Regex 如何在Java中删除字符串中的第一个和最后一个字符? - How to remove first and last character in a string in Java? "计算字符串中的字符出现次数 - Java" - Counting character occurrences in a string - Java 在Java中计算字符串中的字符出现次数 - count character occurrences in a string in Java 获取字符的“前两次”出现之间的子字符串 - Get substring between "first two" occurrences of a character Java 匹配字符串,直到第一次出现不同的字符串 - Java match string until the first occurence of a different string Java - 如何获取字符串中所有出现的特定字符并将它们移动到非预定义位置? - Java - How can one take all occurrences of a specific character in a string and shift them to a non-predefined position?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM