在Java中,我正在尝试编写一个正则表达式来匹配一种特殊的HTTP URL:
http:///#
所以字符串有4个段:
字符串文字:" http:// "; 然后
任何一串1+字符; 然后
字符串文字:" /# "; 然后
任何0+字符串
"传递"字符串的示例:
http://example.com/#
http://example.com/#fizz
http://z.example.com/#
我最好的尝试是:
String regex = "http://*/#*";
但是当我试一试时:
String test = "http://example.com/#"; String regex = "http://*/#*"; if(test.matches(regex)) System.out.println("I match!"); else System.err.println("I don't match!");
我哪里出错了,我的正则表达应该是什么(以及为什么)?
在正则表达式中,如果要匹配1个或多个任何字符,则使用.+
和0或更多使用.*
最好通过一个很好的正则表达式教程,如:http: - regular-expressions.info
你可以使用这个正则表达式:
String regex = "^https?://.+?/#.*$";