删除与正则表达式匹配的所有单词

时间:2014-03-14 04:07:33

标签: java regex

我想从"htsap://"中删除"ftsap://"String等字符序列。有可能吗?
让我用一个例子说明我的需求。

实际输入字符串:

"Every Web page has a http unique address called a URL (Uniform Resource Locator) which identifies where it is located on the Web. For "ftsap://"example, the URL for CSM Library's home page is: "htsap://"www.smccd.edu/accounts/csmlibrary/index.htm The basic parts of a URL often provide \"clues\" to htsap://where a web page originates and who might be responsible for the information at that page or site."

预期的结果字符串:

"Every Web page has a http unique address called a URL (Uniform Resource Locator) which identifies where it is located on the Web. For example, the URL for CSM Library's home page is: www.smccd.edu/accounts/csmlibrary/index.htm The basic parts of a URL often provide \"clues\" to where a web page originates and who might be responsible for the information at that page or site."

我试过的模式:(不太确定它是正确的方式)

((.*?)(?=("htsap://|ftsap://")))

((.*?)(?=("htsap://|ftsap://")))(.*)

有人可以在这里建议吗?

2 个答案:

答案 0 :(得分:1)

由于您在样本String中撤消了引号,我假设您正在使用Java。

你应该尝试:

final String res = input.replaceAll("\"?\\w+://\"?", "");

Here is a link一个关于这个正则表达式完全匹配的工作示例!


工作原理:

匹配并删除任何字母数字字符(和下划线)序列,然后是://,可能在"之前和/或之后。


编辑:如何使用Matcher获得相同的结果?

final String input = "Every Web page has a http unique address called a URL (Uniform Resource Locator) which identifies where it is located on the Web. For \"ftsap://\"example, the URL for CSM Library's home page is: \"htsap://\"www.smccd.edu/accounts/csmlibrary/index.htm The basic parts of a URL often provide \"clues\" to htsap://where a web page originates and who might be responsible for the information at that page or site.";
final Pattern p = Pattern.compile("\"?\\w+://\"?");
final StringBuilder b = new StringBuilder(input);
Matcher m;
while((m = p.matcher(b.toString())).find()) {
    b.replace(m.start(), m.end(), "");
}

System.out.println(b.toString());

答案 1 :(得分:0)

使用此正则表达式:

"(ftsap|htsap).//"

并将其替换为''

正则表达式解释说:

"(ftsap|htsap).//" with flag g

Regular expression visualization

Debuggex Demo