java:用单个空间替换多个空间,并修剪领先和落后空间
regex-inly 虽然读取较少,但使用复杂的正则表达式解决问题是可行的,可以解决问题:
“ x”, “ 1 2 3”, “”, “”, }; for(字符串测试:测试){ system.out.format(“ [%s]%n”, test.replaceall(“^ | $ |()”,“ $ 1”) ); } [solution 1:
trim()删除所有领先和落后的空间,而septaceall()替换空间替换了单个空间。一个步骤中相同的结果。 It matches and replaces sequences of spaces at the beginning, end, or middle of the string with either an empty string (to remove extra spaces) or a single captured space (to keep single spaces intact).
Additional Resources
String after = before.trim().replaceAll(" ", " ");
[String.trim()文档](https://docs.oracle.com/javase/7/docs/api/java/java/lang/lang/string.html#trim----) [正则表达式重复模式] Anchors](https://www.regular-expressions.info/anchors)
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3