【问题标题】:Removing unwanted param from URL variations with REGEX [closed]使用 REGEX 从 URL 变体中删除不需要的参数 [关闭]
【发布时间】:2021-09-28 21:43:42
【问题描述】:

是否有可能从 URI 中删除一些不需要的参数 unwanted,以使最终结果提供正确的 uri?

问题是我想要删除的 url 中有不需要的参数。 我试过了,但是 & 和 ?应该保留在适当的位置以不破坏网址

(unwanted=.*?)\\

https://regex101.com/r/CXEuqH/1

this is clean uri with no params - should remain unchanged 
(should be replaced to: /some-clean-part-of-url-012567):
22 sdff=\"a sdsdsd \" sfs f =\"/some-clean-part-of-url-012567\" saafa 42wsdf=\"sf  sdf sd 432\" asd


url with unwanted only and nothing else:
(should be replaced to: /url-with-unwanted-only):
asda ds3=\"afdaa \" asd ad a =\"/url-with-unwanted-only?unwanted=base-unwanted-value-0605\" aas asd =\"sddghf \"asdasd wsdf=\"sf  sdf sd 432\" a das 


uri with unwanted at the beginning and other one or more wanted params after it
(should be replaced to: /unwanted-at-the-beginning-plus-other-params-4560?wanted_params=wanted_values):
as da=\"hkgd\" a =\"/unwanted-at-the-beginning-plus-other-params-4560?unwanted=not-need-value-23333&wanted_param=wanted_value\" asd =\"sddd8963ghf \" asdasdasd 


uri with unwanted at the end
(should be: unwanted-at-the-end-789870?wanted_param=wanted_value):
asda asd =\"sddwsd333ghf \"asdasdsd as as =\"/unwanted-at-the-end-789870?wanted_param=wanted_value&unwanted=unwanted-value-1-1s\" ad fd df sasd =\"sfe352ddghf \" asdasddf 


uri with unwanted in the middle
(should be: /unwanted-in-the-middle-38642?wanted_param=wanted_value&param_wanted=111):
as asd =\"sfe352ddghf \" as asd asd a =\"/unwanted-in-the-middle-38642?wanted_param=wanted_value&unwanted=some-unwanted-value0313&param_wanted=111\" ad sad asd a asd =\"sfe352ddghf \" as

我试过了,但是 & 和 ?应该保留在适当的位置以不破坏网址

最终结果应该是一个正确的 uri,没有不必要的“&”和“?”最后

【问题讨论】:

  • 这些示例的期望输出是什么?如果你删除“?”从替代比“?”和“&”保持原位。
  • 问题中的每个示例都给出了所需的匹配项。投票重新开放。

标签: regex regexp-replace


【解决方案1】:

你可以使用

(?<=[?&])unwanted=[^&?=\s\\"]*&?

模式匹配:

  • (?&lt;=[?&amp;]) 正向向后看,断言左边是?&amp;
  • unwanted= 字面匹配
  • [^&amp;?=\s\\"]* 重复 0+ 次匹配除了negated character class 中列出的任何字符
  • &amp;? 匹配可选的 & 符号

Regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-09
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多