我有几个页面的当前url:
onclick="location.href='https://www.mydomain.com/shop/bags
在每个url的末尾有这样的内容:
?cid=Black'"
or
?cid=Beige'"
or
?cid=Green'"
我需要的是一个正则表达式在每个url中找到?cid=
,然后替换从?cid=
到结尾的'
的所有内容
目前我有这个:.?cid=.*?'
在每行代码中查找?cid=
的出现。我只希望它在onclick="location.href='https://www.mydomain.com/shop/bags
有人知道这个的解吗?
很抱歉最初的困惑。我使用这个程序http://www.araxis.com/replace-in-files/index-eur.html,它允许使用正则表达式来查找元素。我想它说它允许PERL风格的正则表达式。
谢谢
您可以使用lookaround语法来匹配?cid=something
,前面是URL,后面是'
这个模式应该可以工作:
(?<=Qhttps://www.mydomain.com/shop/bagsE)?cid=[^']++(?=')
如果你用你的替换来替换这个模式,那么从?cid
到'
的整个比特将被替换。
下面是Java中的一个示例(忽略语法的略微不同):
public static void main(String[] args) {
final String[] in = {
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Black'",
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Beige'",
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Green'"
};
final Pattern pattern = Pattern.compile("(?<=\Qhttps://www.mydomain.com/shop/bags\E)\?cid=[^']++(?=')");
for(final String string : in) {
final Matcher m = pattern.matcher(string);
final String replaced = m.replaceAll("SOMETHING_ELSE");
System.out.println(replaced);
}
}
输出onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
显然,这是假设您的工具支持环顾四周。
如果您直接使用Perl,而不是通过您的神奇工具
,这当然可以工作。perl -pi -e '/s/(?<=Qhttps://www.mydomain.com/shop/bagsE)?cid=[^']++(?=')/SOMETHING_ELSE/g' *some_?glob*.pattern
编辑
另一个想法是使用捕获组和反向引用,替换(Qhttps://www.mydomain.com/shop/bagsE)?cid=[^']++
$1SOMETHING_ELSE
Java中的另一个测试用例:
public static void main(String[] args) {
final String[] in = {
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Black'",
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Beige'",
"onclick="location.href='https://www.mydomain.com/shop/bags?cid=Green'"
};
final Pattern pattern = Pattern.compile("(\Qhttps://www.mydomain.com/shop/bags\E)\?cid=[^']++");
for(final String string : in) {
final Matcher m = pattern.matcher(string);
final String replaced = m.replaceAll("$1SOMETHING_ELSE");
System.out.println(replaced);
}
}
输出:onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
onclick="location.href='https://www.mydomain.com/shop/bagsSOMETHING_ELSE'
(onclick="location.href='https://www.mydomain.com/shop/bags.*?)?cid=.*?'
代替$1something'
你可以使用这个模式
?cid=[^']*
这个想法是使用一个字符类来排除最后一个简单的引号,然后避免使用惰性量词。
注意:如果支持的话,您可以使用所有格量词来减少正则表达式引擎的工作量:
?cid=[^']*+