0

我正在寻找一个 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"

我尝试了很多事情都没有成功。

4

4 回答 4

1

您需要更改(a-z)类字符 [a-z],如果您想确定[a-z]+n't部分后还有其他单词,您可以

  • 添加\\S+- 非空格字符 - 在( )括号中并使用此替换 - 您可以使用$xwhere xis group number (在您的情况下可能是$1
  • 使用前瞻机制(?=\\S+),因此这部分不会包含在匹配中,但必须出现在[a-z]+n't.

现在要替换您的数据,您可以使用例如这样的东西

String replacedString = yourString.replaceAll("yourRegex","yourReplacemet");
于 2013-08-23T01:57:39.537 回答
1
    String s = "I don't like having dinner now";
    s =s.replaceAll("(\\w+n't)\\s(\\w+)","not_$2");
    System.out.println(s);

输出:我现在不喜欢吃晚饭

于 2013-09-03T10:23:33.913 回答
0

使用 Pattern 和 Matcher,如下所示:

    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”。

还要注意 +n' 后面的空格。这样单词之间的空格就被删除了,并且输出是 not_like 你要求的,而不是 not_like

记得包含 java.util.regex.Matcher 和 java.util.regex.Pattern!

于 2013-08-23T02:02:29.253 回答
0

你可以试试正则表达式:

[a-z]+n't\s*

例如

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
于 2013-08-23T02:56:59.253 回答