Jay*_*ard 7 php regex regex-lookarounds
我整个早上一直试图让这个正则表达式正确,我已经撞到了墙上.在下面的字符串中,我不想匹配后面的每个正斜杠,.com/<first_word>除了URL / 之后的任何正斜杠.
$string = "http://example.com/foo/12/jacket Input/Output";
match------------------------^--^
Run Code Online (Sandbox Code Playgroud)
斜杠之间的单词长度无关紧要.
正则表达式:(?<=.com\/\w)(\/)结果:
$string = "http://example.com/foo/12/jacket Input/Output"; // no match
$string = "http://example.com/f/12/jacket Input/Output";
matches--------------------^
Run Code Online (Sandbox Code Playgroud)
正则表达式:(?<=\/\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--------------------^-^--------------^
Run Code Online (Sandbox Code Playgroud)
因为lookbehind可以没有修饰符并且需要是一个零长度断言,我想知道我是否刚刚错误的路径并且应该寻找另一个正则表达式组合.
这种正面方式是正面的吗?或者我错过了大量咖啡以外的其他东西?
注:标记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
Run Code Online (Sandbox Code Playgroud)
因此,将每个替换/为在starting之后出现的|afterfirst 。/.com
需要负向后查找来避免在没有像 一样(?<!^)开头的情况下替换字符串。.com/foo/bar/baz/abcd