Java regex replaceAll替换精确值

时间:2016-01-04 06:27:20

标签: java regex

如标题中所述,这是示例输入

我会有这种输入

String str = "test_String test_String#ID\ntest_String#ID test_String";

然后我使用此代码替换上面的代码

regex = "test_String";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(Example1);
str = m.replaceAll("abc");

我得到的输出将成为 " abc#ID abc"

我想要的输出是" test_String#ID abc"

3 个答案:

答案 0 :(得分:2)

您可以使用此基于外观的正则表达式:

regex = "(?m)(?<=\\s|^)test_String(?=\\s|$)";

这意味着仅当test_String被空格或行开头/结尾包围时才匹配String str = "test_String test_String#ID\ntest_String#ID test_String"; String repl = str.replaceAll("(?m)(?<=\\s|^)test_String(?=\\s|$)", "abc");

<强>代码:

abc test_String#ID
test_String#ID abc

<强>输出:

from django.shortcuts import render
...
def home(request):
    ...
    return render(request, 'home.html', 
        { 'img_b64': img.read().encode("base64"),}
    )

答案 1 :(得分:0)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Hello {
    public static void main( String[] args ) {

        String str = "testString#ID testString\ntestString testString#ID";
        String repl = str.replaceAll("(testString)(?!#)", "abc");
        System.out.println(repl);
    }
}

答案 2 :(得分:0)

package com.test;

import java.util.StringTokenizer;

公共类StackOverflow {

public static void main(String[] args) {
    //String Example1 = "testString#ID testString";
    //String Example2 = "testString testString#ID";
    String Example3 = "test_String test_String#ID\ntest_String#ID test_String";
    String regex = "test_String";
    String replaceWIth = "abc";
    String delimiter = " ";
    StringTokenizer tokens  = new StringTokenizer(Example3, delimiter, true);
    // if you want fix the buffer size by 
    // ((Example1.length()/regex.length()) * replaceWIth.length()) + (Example1.length()%regex.length())
    StringBuffer buffer = new StringBuffer();
    while (tokens.hasMoreTokens()) {
        String t = tokens.nextToken(); 
        if (t.equals(regex)) {
            buffer.append(replaceWIth);
        } else {
            buffer.append(t);
        }
    }
    System.out.println(buffer.toString());
}

}