我一直在努力使正则表达式整整整整整整一整天都在碰壁。在下面的字符串中.com/<first_word>
,除了URL/
之后的任何斜杠,我都不会匹配每个正斜杠。
$string = "http://example.com/foo/12/jacket Input/Output";
match------------------------^--^
斜线之间的单词长度应该无关紧要。
正则表达式:(?<=.com\/\w)(\/)
结果:
$string = "http://example.com/foo/12/jacket Input/Output"; // no match
$string = "http://example.com/f/12/jacket Input/Output";
matches--------------------^
正则表达式:(?<=\/\w)(\/)
结果:
$string = "http://example.com/foo/20/jacket Input/O/utput"; // misses the /'s in the URL
matches----------------------------------------^
$string = "http://example.com/f/2/jacket Input/O/utput"; // don't want the match between Input/Output
matches--------------------^-^--------------^
因为后向可以没有修饰符,并且必须是零长度的断言,所以我想知道我是否刚刚走错了路,应该寻求其他正则表达式组合。
积极的眼光背后是这样做的正确方法吗?还是我想念除了大量咖啡以外的东西?
注:标记PHP,因为正则表达式应该在工作的任何的preg_*
功能。
如果要使用,preg_replace
则此正则表达式应该起作用:
$re = '~(?:^.*?\.com/|(?<!^)\G)[^/\h]*\K/~';
$str = "http://example.com/foo/12/jacket Input/Output";
echo preg_replace($re, '|', $str);
//=> http://example.com/foo|12|jacket Input/Output
因此,用启动后出现的后/
一个|
先替换每个。/
.com
(?<!^)
需要使用负向Lookbehind以避免在.com
不像这样开始的情况下替换字符串/foo/bar/baz/abcd
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句