English 中文(简体)
重整
原标题:Replace multiple substrings at once

我有一份档案,其中载有一些案文。 其中有“子1”、“子2”、“子3”等。 我需要用“repl1”、“repl2”、“repl3”等其他一些案文来取代所有这些次。 在沙尔,我就这样说:

{
 "substr1": "repl1",
 "substr2": "repl2",
 "substr3": "repl3"
}

and create the pattern joining the keys with | , then replace with re.sub function. Is there a similar simple way to do this in Java?

最佳回答

这就是说,斯堪的斯堪的斯普森特人是如何把:变为 Java的:

Map<String, String> replacements = new HashMap<String, String>() {{
    put("substr1", "repl1");
    put("substr2", "repl2");
    put("substr3", "repl3");
}};

String input = "lorem substr1 ipsum substr2 dolor substr3 amet";

// create the pattern joining the keys with  | 
String regexp = "substr1|substr2|substr3";

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(input);

while (m.find())
    m.appendReplacement(sb, replacements.get(m.group()));
m.appendTail(sb);


System.out.println(sb.toString());   // lorem repl1 ipsum repl2 dolor repl3 amet

这种办法取代simultanious (即“一度”)。 页: 1

"a" -> "b"
"b" -> "c"

这样,这一办法就可提供<代码>a b”->“b c”,而回答则表明,你应当链条数条打到<代码>replace或replaceAll,该编码可提供c>c>


(如果您将这一办法概括起来,以便按部就班,确保您Pattern.quote ,每一个人检索字和。 替换字数。

问题回答
yourString.replace("substr1", "repl1")
          .replace("substr2", "repl2")
          .replace("substr3", "repl3");

First, a demonstration of the problem:

String s = "I have three cats and two dogs.";
s = s.replace("cats", "dogs")
    .replace("dogs", "budgies");
System.out.println(s);

目的是取代cat =>狗和狗 => budgies,但按顺序进行的更换是根据先前的更换结果进行的,因此,不幸的产出是:

I have three budgies and two budgies.

在此,我同时采用了替代方法。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#regionMatches%28boolean,%20int,%20java.lang.String,%20int,%20int%29”rel=“nofollow”String.regionches :

public static String simultaneousReplace(String subject, String... pairs) {
    if (pairs.length % 2 != 0) throw new IllegalArgumentException(
        "Strings to find and replace are not paired.");
    StringBuilder sb = new StringBuilder();
    int numPairs = pairs.length / 2;
    outer:
    for (int i = 0; i < subject.length(); i++) {
        for (int j = 0; j < numPairs; j++) {
            String find = pairs[j * 2];
            if (subject.regionMatches(i, find, 0, find.length())) {
                sb.append(pairs[j * 2 + 1]);
                i += find.length() - 1;
                continue outer;
            }
        }
        sb.append(subject.charAt(i));
    }
    return sb.toString();
}

测试:

String s = "I have three cats and two dogs.";
s = simultaneousReplace(s,
    "cats", "dogs",
    "dogs", "budgies");
System.out.println(s);

产出:

我有三支狗和两台gie。

此外,有时在同时更换时也是有益的,以确保寻找最长的配对。 (PHP s strtr function do this, for example.) 下面是我执行:

public static String simultaneousReplaceLongest(String subject, String... pairs) {
    if (pairs.length % 2 != 0) throw new IllegalArgumentException(
        "Strings to find and replace are not paired.");
    StringBuilder sb = new StringBuilder();
    int numPairs = pairs.length / 2;
    for (int i = 0; i < subject.length(); i++) {
        int longestMatchIndex = -1;
        int longestMatchLength = -1;
        for (int j = 0; j < numPairs; j++) {
            String find = pairs[j * 2];
            if (subject.regionMatches(i, find, 0, find.length())) {
                if (find.length() > longestMatchLength) {
                    longestMatchIndex = j;
                    longestMatchLength = find.length();
                }
            }
        }
        if (longestMatchIndex >= 0) {
            sb.append(pairs[longestMatchIndex * 2 + 1]);
            i += longestMatchLength - 1;
        } else {
            sb.append(subject.charAt(i));
        }
    }
    return sb.toString();
}

为什么你们需要这样做? 例如下:

String truth = "Java is to JavaScript";
truth += " as " + simultaneousReplaceLongest(truth,
    "Java", "Ham",
    "JavaScript", "Hamster");
System.out.println(truth);

产出:

贾瓦语是 Java语,因为Hamster

如果我们使用<代码>传真而不是<编码>传真<<<>同时语文,则产出将具有“Hamgust”而不是“Hamster”:

请注意,上述方法对个案敏感。 如果您需要对个案敏感的版本,很容易修改上述文本,因为<代码>String.regionMatches/code>可采用ignore。 判例参数。

    return yourString.replaceAll("substr1","relp1").
                     replaceAll("substr2","relp2").
                     replaceAll("substr3","relp3")




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...