简体   繁体   English

如何删除长字符串的前导零

[英]How to remove leading zeros with long string

I'm trying to remove leading zeros from a string where there are multiple other strings and numbers in java我正在尝试从 java 中有多个其他字符串和数字的字符串中删除前导零

so ow -   00250 =     00000000 ]

for the above input I'm trying to get the output to be对于上述输入,我试图让 output 成为

so ow - 250 = 0 ]

I have tried我努力了

removeLeadingZeros(str.trim().replaceAll(" +", " ")

where removeLeadingZeros is removeLeadingZeros 在哪里

    // Regex to remove leading
    // zeros from a string
    String regex = "^0+(?!$)";

    // Replaces the matched
    // value with given string
    str = str.replaceAll(regex, "");

    return str;

but I am getting the output但我得到的是 output

so ow -   00250 =     00000000 ]

which is the same as the original input.这与原始输入相同。

These methods seem to only work for the first element in the string if it is a number such as这些方法似乎只适用于字符串中的第一个元素,如果它是一个数字,例如

00015039 so ow + - 003948 83

which returns返回

15039 so ow + - 003948 83

but want to return但想回来

15039 so ow + - 3948 83

thanks!谢谢!

You can split the string at each space character, then process each substring through your function, and then join them together again.您可以在每个空格字符处拆分字符串,然后通过您的 function 处理每个 substring,然后再次将它们连接在一起。

String[] substrings = myString.split(" ", 0);
for (int i = 0; i < substring.length; i++) {
    substrings[i] = removeLeadingZeros(substrings[i]);
}
myString = String.Join(" ", substrings);

Please excuse any typos.请原谅任何错别字。 I'm writing this from my phone, so I haven't been able to put it through its paces.我正在用手机写这篇文章,所以我无法完成它的步伐。 Hopefully the general idea comes through.希望总体思路能够通过。

By splitting the given string into array and then remove the leading zeroes, is working fine.通过将给定的字符串拆分为数组,然后删除前导零,工作正常。

where removeLeadingZeros is:其中 removeLeadingZeros 是:

public static  String removeLeading(String str) {
String regex = "^0+(?!$)";
String x[] = str.split(" ");
StringBuilder z = new StringBuilder();
    
for(String y:x) {
    str = y.replaceAll(regex, "");
    z.append(" " + str);
}
return z.toString();
}

tl;dr tl;博士

Arrays
.stream( input.split( " " ) )
.filter( s -> ! s.isBlank() ) 
.map(
    s -> {
        try{
            return String.valueOf( Integer.parseInt( s ) ) ; 
        } catch ( NumberFormatException e ) {
            return s ; 
        }
    }
)
.collect( Collectors.joining( " " ) )

Split into parts, parsing each as an int拆分为多个部分,将每个部分解析为int

I would split the string into parts, delimiting by SPACE character.我会将字符串分成几部分,用空格字符分隔。

input.split( " " )

Splitting results in an array.拆分结果为数组。 Make a stream of that array.制作该数组的 stream 。

String input = "so ow -   00250 =     00000000 ]" ;
String output = 
    Arrays
    .stream( input.split( " " ) )
…

All those extra spaces will result in a bunch of chunks that are empty strings, no text within.所有这些额外的空格将导致一堆空字符串,其中没有文本。 So filter those out.所以过滤掉那些。

And we want to eliminate whitespace as well as empty strings, so call String#isBlank rather than String#isEmpty .我们想消除空格和空字符串,所以调用String#isBlank而不是String#isEmpty

.filter( s -> ! s.isBlank() ) 

Try to parse each part as an integer number.尝试将每个部分解析为 integer 编号。 If the parsing fails, an exception is thrown.如果解析失败,则抛出异常。 Trap for that exception.捕获该异常。 If caught, simply return the text we tried and failed to parse.如果被捕获,只需返回我们尝试过但未能解析的文本。 If no exception, return a string of the newly minted int value.如果没有异常,则返回一个新生成的int值的字符串。

.map(
    s -> {
        try{
            int x = Integer.parseInt( s ) ;
            return String.valueOf( x ) ; 
        } catch ( NumberFormatException e ) {
            return s ;  // Swallow the exception.
        }
    }
)

Collect all our remaining and newly-created parts with a SPACE as their delimiter.收集我们所有剩余的和新创建的部分,并以空格作为分隔符。

.collect( Collectors.joining( " " ) )

Code example代码示例

Pulling all that code together looks like this:将所有这些代码放在一起看起来像这样:

String input = "so ow -   00250 =     00000000 ]" ;
String output = 
    Arrays
    .stream( input.split( " " ) )
    .filter( s -> ! s.isBlank() ) 
    .map(
        s -> {
            try{
                int x = Integer.parseInt( s ) ;
                return String.valueOf( x ) ; 
            } catch ( NumberFormatException e ) {
                return s ;  // Swallow the exception.
            }
        }
    )
    .collect( Collectors.joining( " " ) )
;
System.out.println( output ) ;

See that code run live at IdeOne.com .请参阅在 IdeOne.com 上实时运行的代码

so ow - 250 = 0 ]所以 ow - 250 = 0 ]

You can use您可以使用

String result = text.replaceAll("\\b(?<!\\d[,.])(?:(0)+\\b|0+(?=[1-9]))", "$1").replaceAll("(?U)\\s+", " ").trim();

See the regex demo .请参阅正则表达式演示

Depending on how messy your input is you might need to adjust or even expand the solution.根据您输入的混乱程度,您可能需要调整甚至扩展解决方案。 Details :详情

  • \b(?<,\d[..]) - a word boundary, there must be start of string or a non-word char immediately to the right, and there can be no digit + a dot or a comma immediately to the left of the current location (that is, we exclude the decimal digit matching) \b(?<,\d[..]) - 单词边界,右侧必须有字符串开头或非单词字符,并且不能有数字+点或逗号紧邻当前位置的左边(即我们排除十进制数字匹配)
  • (?:(0)+\b|0+(?=[1-9])) - either of the two patterns: (?:(0)+\b|0+(?=[1-9])) - 两种模式之一:
    • (0)+\b - 0 , one or more times, the last 0 is saved in Group 1, followed with a word boundary (0)+\b - 0 ,一次或多次,最后一个0保存在 Group 1 中,后跟一个单词边界
    • | - or - 或者
    • 0+(?=[1-9]) - one or more 0 chars followed with a non-zero digit. 0+(?=[1-9]) - 一个或多个0字符后跟一个非零数字。

.replaceAll("(?U)\\s+", " ") shrinks any Unicode whitespace character chunks into a single ASCII space. .replaceAll("(?U)\\s+", " ")将任何 Unicode 空白字符块收缩到单个 ASCII 空间中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM