Java正则表达式替换n个空格,其中只存在n个,而不存在n+-1或n+-1
嗨,这真的让我很烦恼,我就是搞不懂正则表达式 我想要一个正则表达式,它可以用'♥', 但只有在有n个空格的情况下,不多也不少 伪代码:Java正则表达式替换n个空格,其中只存在n个,而不存在n+-1或n+-1,java,regex,Java,Regex,嗨,这真的让我很烦恼,我就是搞不懂正则表达式 我想要一个正则表达式,它可以用'♥', 但只有在有n个空格的情况下,不多也不少 伪代码: String myReplaceFunction(String text, String replaceThis, String withThis, int countOfConcecutive); String originalString =" This is a very short text . "; String
String myReplaceFunction(String text, String replaceThis, String withThis, int countOfConcecutive);
String originalString =" This is a very short text . ";
String regexMagicString = myReplaceFunction(" ", "♥", 4);
System.out.println(regexMagicString); // "♥This is a very♥short♥text♥. "
这似乎有效,不需要向后看或向前看:
/(^|\S)\s{4}(\S|$)/
记得换成1美元♥$2.由于此空白可能排除换行符,\s不可能
s = s.replace("(?<![ \t])[ \t]{13}(?![ \t])", "♥");
对于空白:[\t]。
消极的回头看:?-零宽度。
消极展望:?![\t]
我没有测试它。代码
后果
注意:输入在后面包含5个空格。那是不会被取代的
输入
输出
解释
? 反向查找确保前面的不是空格字符
{4} 将空格字符精确匹配4次
?! 负前瞻确保后面的不是空格字符
显示您的正则表达式尝试及其输出。您可以创建包含所需数字的模式。类似于\\s{+nbSpace+}的内容,但如果没有。PS:您在函数调用中忘记了originalString参数。您可以共享myReplaceFunction的代码吗?这非常详细。你不必为我写一个例子,但解释部分确实是我所需要的。我尝试过各种组合,但几个小时后我不得不承认我对正则表达式的理解还不够透彻。正如你所解释的,我需要的是向后看和向前看。直到现在我才理解这个功能以及如何使用它。谢谢lot@SimonKaae不客气。我更改了使用代码,使其更接近您试图创建的方法。它还正确地引用了正则表达式字符串,而不是数字,因为它是一个int,这样你就不会发生奇怪的事情,例如,如果你试图替换。用什么东西。我喜欢提供详细的回答,因为答案往往缺乏信息/解释。如果未来的读者正在寻找类似的解决方案,它也可能对他们有所帮助。
(?<! ) {4}(?! )
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final String string = " This is a very short text . ";
final String replace = " ";
final String subst = "♥";
String result = myReplaceFunction(string, replace, subst, 4);
System.out.println(result);
}
public static String myReplaceFunction(String text, String replaceThis, String withThis, int countOfConsecutive) {
replaceThis = Pattern.quote(replaceThis);
final String regex = String.format("(?<!%1$s)%1$s{%2$s}(?!%1$s)", replaceThis, countOfConsecutive);
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(text);
final String result = matcher.replaceAll(withThis);
return "Substitution result: " + result;
}
}
This is a very short text .
♥This is a very♥short♥text♥.