简体   繁体   English

如何在Java中删除字符串开头而不是制表符的空格?

[英]How to remove spaces at the beginnig of a string but not tabs in Java?

I, have to remove leading whitespace from a string except the \\t character. I,必须从\\ t字符之外的字符串中删除前导空格。 For example 例如

" \\thello"

should become 应该成为

"\\thello"

I've tried with 我尝试过

stringToTrim = stringToTrim.replaceAll("^\\s+", "");

but the regex match also with tab character and the result is 但是正则表达式也与制表符匹配,结果是

"hello"

Is it possible to remove leading whitespaces but not tabs with regex? 是否可以使用正则表达式删除前导空格,但不能删除制表符?

In Java, you may use a character class subtraction to restrict a more generic pattern. 在Java中,可以使用字符类减法来限制更通用的模式。

Use 采用

stringToTrim = stringToTrim.replaceFirst("^[\\s&&[^\t]]+", "");

Here, 这里,

  • ^ - matches the start of string ^ -匹配字符串的开头
  • [ - start of a character class [ -角色类的开始
  • \\\\s - any whitespace pattern \\\\s任何空格模式
  • && - intersection operator && -交集运算符
  • [^\\t] - any char but a tab [^\\t] -除制表符外的任何字符
  • ] - end of the character class ] -字符类的结尾
  • + - a quantifier matching one or more occurrences. + -与一个或多个匹配项匹配的量词。

Note since there will only be 1 replacement, it makes sense to use .replaceFirst rather than .replaceAll . 注意,由于只有1个替换,因此使用.replaceFirst而不是.replaceAll是有意义的。

如果您只对空白感兴趣,那么stringToTrim.replaceFirst("^ *", "")将为您服务。

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

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