如何解决替换匹配的正则表达式的子字符串
| 我获取了一些html并进行了一些字符串操作,并添加了像这样的字符串string sample = \"\\n \\n 2 \\n \\n \\ndl. \\n \\n \\n flour\\n\\n \\n 4 \\n \\n cups of \\n\\nsugar\\n\"
我想找到所有成分行并删除空格和换行符
2 dl。面粉和4杯糖
到目前为止,我的方法是进行以下操作。
Pattern p = Pattern.compile(\"[\\\\d]+[\\\\s\\\\w\\\\.]+\");
Matcher m = p.matcher(Result);
while(m.find()) {
// This is where i need help to remove those pesky whitespaces
}
解决方法
以下代码应为您工作:
String sample = \"\\n \\n 2 \\n \\n \\ndl. \\n \\n \\n flour\\n\\n \\n 4 \\n \\n cups of \\n\\nsugar\\n\";
Pattern p = Pattern.compile(\"(\\\\s+)\");
Matcher m = p.matcher(sample);
sb = new StringBuffer();
while(m.find())
m.appendReplacement(sb,\" \");
m.appendTail(sb);
System.out.println(\"Final: [\" + sb.toString().trim() + \']\');
输出值
Final: [2 dl. flour 4 cups of sugar]
,sample = sample.replaceAll(\"[\\\\n ]+\",\" \").trim();
输出:
2 dl. flour 4 cups of sugar
开头没有空格,结尾没有空格。
它首先用一个空格替换所有空格和换行符,然后从乞求/结尾处修剪多余的空格。
,我认为这样的事情将为您工作:
String test = \"\\n \\n 2 \\n \\n \\ndl. \\n \\n \\n flour\\n\\n \\n 4 \\n \\n cups of \\n\\nsugar\\n\";
/* convert all sequences of whitespace into a single space,and trim the ends */
test = test.replaceAll(\"\\\\s+\",\" \");
,我以为\\n
不是实际的换行符,但它也可以与linefeeds
一起使用。
这应该工作正常:
test=test.replaceAll (\"(?:\\\\s|\\\\\\n)+\",\" \");
如果没有ѭ10,可能会更简单:
test=test.replaceAll (\"\\\\s+\",\" \");
您需要修剪前导/尾随空格。
我使用RegexBuddy工具来检查任何单个正则表达式,使用这么多种语言非常方便。
,您应该能够使用标准的String.replaceAll(String,String)。第一个参数采用您的模式,第二个参数采用空字符串。
,s/^\\s+//s
s/\\s+$//s
s/(\\s+)/ /s
运行这三个替换(不替换任何开头的空白,不替换任何结尾的空白,用一个空格替换多个空白)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。