【问题标题】:Regex to match spaces except for spaces inside url pattern正则表达式匹配空格,除了 url 模式内的空格
【发布时间】:2013-06-04 03:33:44
【问题描述】:

您好,我是正则表达式的新手,我正在尝试使用它来捕获垃圾中的空格 \s{2,},但 包括 "url":"https://x.com/a/C25/XPS - Connection - May 2013.docx" 中的空格。目前,我有一个 url 尚未编码的场景,因此它可能包含空格。

示例文本:

"startofjunk      junkjunkjunkjunk","url":"https://x.com/a/C25/XPS  - Connection - May 2013.docx","contentsource":"AX","returpath":null,"detailpath":"https://ax.sample.com/Rep>ositories/form.aspx?path=C25/96/99&mode=Read","detailspath2":"samplepath"

所需文字:

"startofjunk junkjunkjunkjunk","url":"https://x.com/a/C25/XPS  - Connection - May 2013.docx","contentsource":"AX","returpath":null,"detailpath":"https://ax.sample.com/Rep>ositories/form.aspx?path=C25/96/99&mode=Read","detailspath2":"samplepath"

请帮忙。谢谢

【问题讨论】:

    标签: regex spaces


    【解决方案1】:

    说明

    这个正则表达式会找到一个用一个空格替换所有多个空格,并且会绕过 url 部分。在 X 个空格的序列中,第一个空格被放入第 1 组,该组作为\1 馈送到输出,而其他空格将被忽略。 URL 部分被绕过,因为如果它作为| or 语句的一部分遇到,那么它会被捕获到组 2 中,然后由\2 替换注入回输出中。

    正则表达式:(\s)\s*|("url":"[^"]*"),替换为:\1\2

    源字符串

    "startofjunk        junkjunkjunkjunk","url":"https://x.com/a/C25/XPS - Connection - May 2013.docx","contentsource":"AX","returpath":null,"detailpath":"https://ax.sample.com/Rep>ositories/form.aspx?path=C25/96/99&mode=Read","detailspath2":"samplepath"
    

    PHP 示例

    包含这个 php 示例只是为了说明正则表达式的工作原理

    <?php
    $sourcestring="your source string";
    echo preg_replace('/(\s)\s*|("url":"[^"]*")/im','\1',$sourcestring);
    ?>
    
    $sourcestring after replacement:
    "startofjunk junkjunkjunkjunk","url":"https://x.com/a/C25/XPS - Connection - May 2013.docx","contentsource":"AX","returpath":null,"detailpath":"https://ax.sample.com/Rep>ositories/form.aspx?path=C25/96/99&mode=Read","detailspath2":"samplepath"
    

    【讨论】:

    • 嗨@Denomales 谢谢!我们应该添加什么来将匹配的空格修改为单个空格?像这样:“startofjunk junkjunkjunkjunk”
    【解决方案2】:

    使用前瞻来断言您的空格出现在“url”之前。还可以使用后视功能,这样您的整个匹配就是多余的空格:

    (?<=\s)\s+(?=.*"url":)
    

    要删除多余的空格,请将整个匹配项替换为空白(即没有),或者如果您的应用程序语言允许,删除整个匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多