java - 如何在java中执行preg_replace_all

标签 java regex

我有一个 wsdl 文件,其 url 分散在其中,我喜欢将部分 url 替换为其他出现的内容

例如,这里是 wsdl 文件的一部分

<definitions xmlns:tns="http://local.host/web/test/11/soap/testserver.php" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" name="DatixInterface" targetNamespace="http://local.host/web/test/11/soap/testserver.php">

我喜欢将所有“http://local.host/web/test/11 ”替换为“http://web.server/ ”,所以它看起来像这样

<definitions xmlns:tns="http://web.server/soap/testserver.php" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" name="DatixInterface" targetNamespace="http://web.server/soap/testserver.php">

我可以在 php 中使用 preg_replace_all 轻松地做到这一点,但我似乎无法在 java 中做到这一点。

(我的主要语言不是 java,所以提前抱歉)

非常感谢任何帮助,并提前致谢

最佳答案

您可以使用简单的文本编辑器来完成此操作。

但是您也可以使用sedawkperl。您可以在此处查看 sed 示例: http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.html

使用 sed 你可以这样做:

sed -i .bak 's#http://local.host/web/test/11#http://web.server/#' yourfile.wsdl

对于java,您可以使用简单的字符串轻松完成此操作。替换:

public class Test{

    public static void main(String[] args) {
        String sentence = "<definitions xmlns:tns=\"http://local.host/web/test/11/soap/testserver.php\" xmlns:soap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns=\"http://schemas.xmlsoap.org/wsdl/\" name=\"DatixInterface\" targetNamespace=\"http://local.host/web/test/11/soap/testserver.php\">";

        String str = sentence.replaceAll("http://local.host/web/test/11", "http://web.server/");
        System.out.println(str);
    }
}

顺便说一句,如果你想加载文件的内容并替换这些字符串,你可以使用好 friend Apache commons:

File file = new File("D:\\yourfile.wsdl");
String fileString = FileUtils.readFileToString(file);
String finalString = fileString.replaceAll("http://local.host/web/test/11", "http://web.server/");
FileUtils.writeStringToFile(file, finalString);

关于java - 如何在java中执行preg_replace_all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633652/

相关文章:

java - 如何将带有嵌套枚举的枚举对象作为参数传递给方法?

c# - 如何为给定示例制定正则表达式

java - 正则表达式 - 包含多个下划线的单词

java - 如何在 Netbeans 中运行 cucumber 功能文件

Java观察者与策略的结合?

Java JTable 不可见

regex - 从 RedHat Linux 7 中的文件输出特定字符串 - 可能是正则表达式

regex - 将长正则表达式拆分为多行?

javascript - 无法用单引号或双引号跨越 html 文本换行

java - 基于其paintComponent的可滚动JPanel