[英]String manipulation in java using replaceAll()
I have string of the following form: 我有以下形式的字符串:
भन्ने [-0.4531954191090929, 0.7931147934270654, -0.3875088408737827, -0.09427394940704822, 0.10065554475134718, -0.22044284832864797, 0.3532556916833505, -1.8256229909222224, 0.8036832111904731, 0.3395868096795993]
Whereever [ or ] or ,
char are present , I just want to remove them and i want each of the word and float separated by a space. 无论存在
[ or ] or ,
char,我只想删除它们,并且我想将单词和浮点数中的每一个都用空格隔开。 It is follows: 如下:
भन्ने -0.4531954191090929 0.7931147934270654 -0.3875088408737827 -0.09427394940704822 0.10065554475134718 -0.22044284832864797 0.3532556916833505 -1.8256229909222224 0.8036832111904731 0.3395868096795993
I am representing each of these string as line
. 我将每个字符串表示为
line
。 i did following: 我做了以下:
line.replaceAll("([|]|,)$", " ");
But it didn't work for me. 但这对我没有用。 There was nothing change in the input line.
输入行没有任何变化。 Any help is really appreciated.
任何帮助都非常感谢。
Strings are immutable. 字符串是不可变的。 Try
尝试
line = line.replaceAll("([|]|,)$", " ");
Or to be a bit more verbose, but avoiding regular expressions: 或者更详细些,但避免使用正则表达式:
char subst = ' ';
line = line.replace('[', subst).replace(']', subst).replace(',', subst);
In Java, strings are immutable , meaning that the contents of a string never change. 在Java中,字符串是不可变的 ,这意味着字符串的内容永远不会改变。 So, calling
所以,打电话
line.replaceAll("([|]|,)$", " ");
won't change the contents of line
, but will return a new string. 不会更改
line
的内容,但是会返回一个新字符串。 You need to assign the result of the method call to a variable. 您需要将方法调用的结果分配给变量。 For instance, if you don't care about the original
line
, you can write 例如,如果您不在乎原始
line
,则可以编写
line = line.replaceAll("([|]|,)$", " ");
to get the effect you originally expected. 达到您最初预期的效果。
[
and ]
are special characters in a regular expression. [
和]
是正则表达式中的特殊字符。 replaceAll is expected a regular expression as its first input, so you have to escape them. replaceAll应该作为正则表达式作为其第一个输入,因此您必须对其进行转义。
String result = line.replaceAll("[\\[\\],]", " ");
Cannot tell what you were trying to do with your original regex, why you had the $ there etc, would need to understand what you were expecting the things you put there to do. 无法告诉您您想使用原始正则表达式做什么,为什么在那里有$等,则需要了解您对放置在其中的事情的期望。
Try 尝试
line = "asdf [foo, bar, baz]".replaceAll("(\\[|\\]|,)", "");
The regex syntax uses []
to define groups like [az]
so you have to mask them. regex语法使用
[]
定义类似[az]
因此您必须屏蔽它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.