【问题标题】:Python Regex Match Before Character AND Ignore White SpacePython 正则表达式匹配字符前并忽略空格
【发布时间】:2026-01-26 13:25:01
【问题描述】:

我正在尝试编写一个正则表达式来匹配 '/' 之前的字符串的一部分,但同时忽略匹配中的任何前导或尾随空格。

到目前为止,我有 ^[^\/]* 匹配“/”之前的所有内容,但我不知道如何忽略空格。

      123 / some text 123

应该让步

123

     a test / some text 123

应该让步

a test

【问题讨论】:

    标签: python regex


    【解决方案1】:

    这有点棘手。您首先从非空白字符开始匹配,然后继续缓慢但肯定地匹配到紧跟可选数量的空格和斜线标记的位置:

    \S.*?(?= *\/)
    

    live demo here

    如果斜线标记可能是输入字符串中的第一个非空白字符,则将\S 替换为[^\s\/]

    [^\s\/].*?(?= *\/)
    

    【讨论】:

      【解决方案2】:

      这个表达式是你可能想要探索的:

      ^(.*?)(\s+\/.*)$
      

      在这里,我们有两个捕获组,第一个收集您想要的输出,第二个是您不想要的模式,以开始和结束字符为界,为了安全起见,如果您愿意,可以将其删除:

      (.*?)(\s+\/.*)
      

      Python 测试

      # coding=utf8
      # the above tag defines encoding for this document and is for Python 2.x compatibility
      
      import re
      
      regex = r"^(.*?)(\s+\/.*)$"
      
      test_str = ("123 / some text 123\n"
          "anything else    / some text 123")
      
      subst = "\\1"
      
      # You can manually specify the number of replacements by changing the 4th argument
      result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
      
      if result:
          print (result)
      
      # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
      

      JavaScript 演示

      const regex = /^(.*?)(\s+\/.*)$/gm;
      const str = `123 / some text 123
      anything else    / some text 123`;
      const subst = `\n$1`;
      
      // The substituted value will be contained in the result variable
      const result = str.replace(regex, subst);
      
      console.log('Substitution result: ', result);

      正则表达式

      如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。

      正则表达式电路

      您还可以在jex.im 中可视化您的表达式:

      空格

      对于您想要的输出之前的空格,我们可以简单地使用negative lookbehind添加一个捕获组:

       ^(\s+)?(.*?)(\s+\/.*)$
      

      JavaScript 演示

      const regex = /^(\s+)?(.*?)(\s+\/.*)$/gm;
      const str = `      123 / some text 123
                   anything else    / some text 123
      123 / some text 123
      anything else    / some text 123`;
      const subst = `$2`;
      
      // The substituted value will be contained in the result variable
      const result = str.replace(regex, subst);
      
      console.log('Substitution result: ', result);

      Demo

      【讨论】:

      • (.*?)(\s+\/.*) 如果字符串以空格开头,则不起作用,您如何看待将其更改为 "\s*(.*?)(\ s+\/.*)"
      • 使用 (\s+) 有什么特别的原因吗?而不是 \s*。它们在我看来是一样的。我正在对正则表达式进行某种研究,对人们的偏好感到好奇?
      • @Peipei “它们在我看来是一样的。”——实际上非常不同。在这种情况下,\s+ 要求在 / 之前有一个空格。 \s* 不会,因此即使没有空格,正则表达式也会匹配,例如 abc/。问题中的所有示例在 / 之前都有一个空格,所以(在没有特定要求的情况下)我认为\s+ 在这里是正确
      • @zdim,我要比较的是(\s+)?和 \s*,而不是 \s+ 和 \s*。显然 (\s+)?不匹配空格。
      • @Peipei 哦,我没有意识到? 是其中的一部分。然后看起来他们之间没有区别,除了可能在效率上。
      【解决方案3】:

      这是一个可能的解决方案

      正则表达式

      (?<!\/)\S.*\S(?=\s*\/)
      

      示例

      # import regex # or re
      
      string = ' 123 / some text 123'
      test = regex.search(r'(?<!\/)\S.*\S(?=\s*\/)', string)
      print(test.group(0))
      # prints '123'
      
      string = 'a test / some text 123'
      test = regex.search(r'(?<!\/)\S.*\S(?=\s*\/)', string)
      print(test.group(0))
      # prints 'a test'
      

      简短说明

      • (?&lt;!\/) 表示在可能的匹配之前不能有 / 符号。
      • \S.*\S 延迟匹配 anything (.*),同时确保它不以空格开头或结尾 (\S)
      • (?=\s*\/) 表示可能的匹配必须后跟 / 符号或空格 + /

      【讨论】:

        【解决方案4】:

        你可以不用正则表达式

        my_string = "      123 / some text 123"
        match = my_string.split("/")[0].strip()
        

        【讨论】:

        • 不错!一个不是很有用但很有趣的测试用例:my_string = " / something"。这里不同的方法各不相同:您的解决方案返回一个空字符串,而正则表达式返回 None
        最近更新 更多