[英]Replace comma with a comma followed by space
Due to the way server-side data is formatted I need to reformat it with my own function and to prevent any unwanted reformatting I want to check if the string I'm reformatting needs to be reformatted. 由于服务器端数据的格式化方式,我需要使用自己的函数将其重新格式化,并防止任何不必要的重新格式化,我想检查要重新格式化的字符串是否需要重新格式化。
Here is the condition and the regex involved. 这是条件和涉及的正则表达式。
String value = "test, test, test.";
if (!value.matches("/(\\s*, )/g")) {
return value.replaceAll(",", ", ");
}
else {
return value;
}
The expected result is if a string is: Test,test,test
it will reformat it to Test, test, test
. 预期的结果是,如果字符串为: Test,test,test
,它将重新格式化为Test, test, test
。
The behavior I am getting is that even the value
string in the code goes into the if
condition when it should skip it and go into the else
. 我得到的行为是,即使代码中的value
字符串在应跳过它并进入else
时也进入if
条件。
The best solution found here for me was ",(?! )", ", "
but it solved a problem I didn't even have so I simplified it to ",(\\\\S)", ", $1"
. 在这里为我找到的最佳解决方案是",(?! )", ", "
但是它解决了我什至没有的问题,因此我将其简化为",(\\\\S)", ", $1"
。
The proposed solution would add a 建议的解决方案将添加一个 after
,
even if the ,
would be at the end of the string which is something I didn't want. 之后,
即使,
是在字符串的结尾这是一件好事,我不想。
Also in my question, I had a redundant if
condition which I removed and simplified the solution to: 同样在我的问题中,我有一个多余的if
条件,该条件已删除并将其简化为:
String value = "Test,test,test";
return value.replaceAll(",(\\S)", ", $1");
Output: 输出:
Test, test, test
You don't need to check, you can just use : 您无需检查,只需使用:
value = value.replaceAll("\\s*,\\s*", ", ");
Input for example : 输入例如:
test , test, test.
Output 输出量
test, test, test.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.