嗨,这真让我烦恼,我只是想弄清楚正则表达式。
我想要一个可以用'♥'替换n个连续空格的正则表达式,但前提是只有正好n个空格且不多或不少。
伪代码:
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♥. "
答案 0 :(得分:1)
这似乎有用(不需要后视或前瞻):
/(^|\S)\s{4}(\S|$)/
请记住将其替换为$1♥$2
。
答案 1 :(得分:0)
由于这个空格可能排除了换行符\s
,因此无法实现。
s = s.replace("(?<![ \t])[ \t]{13}(?![ \t])", "♥");
[ \t]
。(?<![ \t])
- 零宽度。(?![ \t])
我没有测试过。
答案 2 :(得分:0)
(?<! ) {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;
}
}
注意:输入包含.
后未被替换的5个空格。
This is a very short text .
♥This is a very♥short♥text♥.
(?<! )
否定的背后隐藏确保前面的内容不是空格字符
{4}
恰好匹配空格字符4次(?! )
否定前瞻确保后面的内容不是空格字符