我正在寻找一个java正则表达式来替换模式的任何字符串,
(a-z)+n't (word)
至not_word
例如:
"doesn't like" to "not_like"
"I don't like" to "i not_like"
"I don't like having dinner now" to "I not_like having dinner now"
我做了很多事但没有成功。
答案 0 :(得分:1)
您需要将(a-z)
更改为class character [a-z]
,如果您想确保[a-z]+n't
部分之后还有其他字词
\\S+
(
括号中添加)
- 非空格字符,并使用此group代替 - 您可以使用$x
x
1}}是组号(在您的情况下,它可能是$1
)(?=\\S+)
,因此此部分不会包含在匹配中,但必须在[a-z]+n't
之后显示。现在要替换您可以使用的数据,例如
String replacedString = yourString.replaceAll("yourRegex","yourReplacemet");
答案 1 :(得分:1)
String s = "I don't like having dinner now";
s =s.replaceAll("(\\w+n't)\\s(\\w+)","not_$2");
System.out.println(s);
输出:我现在不喜欢吃晚餐
答案 2 :(得分:0)
使用模式和匹配器,如下所示:
String text ="doesn't like"
String patternString1 = "([a-zA-Z]+n't )";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
String replaceAll = matcher.replaceAll("not_");
System.out.println("replaceAll = " + replaceAll);
结果将是:“not_like”
[a-zA-Z]确保它也替换了单词的开头,否则它会输出“doesnot_like”。
注意+之后的空格。这样就可以删除单词之间的空格,并且输出结果与你请求的不相似,而不是像
那样请记住包含java.util.regex.Matcher和java.util.regex.Pattern!
答案 3 :(得分:0)
您可以尝试使用正则表达式:
[a-z]+n't\s*
e.g。
private static final Pattern REGEX_PATTERN =
Pattern.compile("[a-z]+n't\\s*",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
public static void main(String[] args) {
String input = "doesn't like\nI don't like\nI don't like having dinner now";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("not_")
);
}
输出:
not_like
I not_like
I not_like having dinner now