Java 替换匹配正则表达式的子字符串
我获取一些html并进行一些字符串操作,然后使用类似Java 替换匹配正则表达式的子字符串,java,regex,string,removing-whitespace,Java,Regex,String,Removing Whitespace,我获取一些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 =
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
}
您应该能够使用标准。第一个参数将采用您的模式,第二个参数将采用空字符串
s/^\s+//s
s/\s+$//s
s/(\s+)/ /s
运行这三个替换(将前导空格替换为零,将尾随空格替换为零,将多个空格替换为一个空格。我认为这样的方法对您很有用:
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+", " ");
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() + ']');
sample=sample.replaceAll(“[\\n]+”,”).trim();
输出:
2 dl.面粉4杯糖
开头没有空格,结尾也没有空格
它首先用一个空格替换所有空格和换行符,然后从begging/end修剪多余的空格。以下代码适用于您:
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+", " ");
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() + ']');
输出
我假设
\n
不是实际的换行符,但它也适用于换行符。
这应该很好:
test=test.replaceAll(“(?:\\s\124;\\\ n)+”,”;
如果没有文本\n
可以更简单:
test=test.replaceAll(“\\s+”,”);
a您需要修剪前导/尾随空格
我使用RegexBuddy工具来检查任何一个正则表达式,在许多语言中都非常方便。这就是我需要正则表达式变量的地方,我真的不知道如何使用。让我举例说明:我的模式匹配“\n\n 2\n\n\ndl。\n\n\n面粉\n\n\n\n”我想用“2 dl.面粉”来代替它。我这里的问题是如何从匹配的子字符串中提取信息?@Flexo,请看我的回答,它正是这样做的。您的解决方案正是我想要的,我明天会尝试。顺便说一句,\n包含在\s中,因此您的模式中只需要[\\s]+为什么不使用replaceAll()
和其他人一样?是的,可以使用replaceAll()
也一样,但OP试图使用模式/匹配器类来实现这一点,所以编写了使用该类的代码。事实上,我使用模式/匹配器的原因是字符串也包含其他内容,但这是实际的配方。我只想格式化成分,以便它们可以显示在一个漂亮的列表中。要匹配文字序列\n
(反斜杠+n'),您需要在正则表达式中使用四个反斜杠(\\\\n
),而不是三个。但很明显,OP确实在尝试匹配换行符。