如何匹配这样的 URL 字符串:
img src =“https://stackoverflow.com/a/b/c/d/someimage.jpg”
其中只有域名和文件扩展名(jpg)是固定的,其他都是变量?
以下代码似乎不起作用:
Pattern p = Pattern.compile("<img src=\"http://stachoverflow.com/.*jpg");
// Create a matcher with an input string
Matcher m = p.matcher(url);
while (m.find()) {
String s = m.toString();
}
最佳答案
与您提供的示例字符串匹配的正则表达式存在一些问题。不过,你已经很接近了。这是您的代码已修复以使其正常工作:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPChat {
static public void main(String[] args) {
String url = "<img src=\"http://stackoverflow.com/a/b/c/d/someimage.jpg\">";
Pattern p = Pattern.compile("<img src=\"http://stackoverflow.com/.*jpg\">");
// Create a matcher with an input string
Matcher m = p.matcher(url);
while (m.find()) {
String s = m.toString();
System.out.println(s);
}
}
}
关于Java 正则表达式匹配器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2573534/