简体   繁体   English

用replaceAll删除部分字符串

[英]remove part of string with replaceAll

I'm trying to delete the beginning of the following sentence from a file: 我正在尝试从文件中删除以下句子的开头:

size: 尺寸:

size : 大小:

The issue is with the space between " : ". 问题在于“ ”之间的空间。 I have tried many regular expressions using some help from https://regex101.com/ but none of them works for me. 我使用https://regex101.com/的一些帮助尝试了许多正则表达式,但它们都不适用于我。

My code: 我的代码:

String myString= in.nextLine();
myString.replaceAll("size$:", "");
int n = Integer.parseInt(myString);

You can use this regex size\\s*: which mean replace size followed by zero or more spaces followed by : like so : 您可以使用此正则表达式size\\s*:这意味着替换大小后跟零或更多空格,后跟:如下所示:

myString = myString.replaceAll("size\\s*:", "");

regex demo 正则表达式演示


Note that Strings in Java are immutable so you have to assign the result of replaceAll to your String else myString will not be changed even your replaceAll work fine. 请注意,Java中的字符串是不可变的,因此您必须将replaceAll的结果分配给您的字符串,否则即使您的replaceAll工作正常, myString也不会被更改。


If you want to delete only the "size\\s:" strings from the beginning of your line, you can just add ^ anchor to your regex which mean beginning of line, so it will be like this : 如果你想从你的行的开头只删除"size\\s:"字符串,你可以将^ anchor添加到你的正则表达式,这意味着行的开头,所以它将是这样的:

myString = myString.replaceAll("^size\\s*:", "");

regex demo 正则表达式演示

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

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