首页 > 解决方案 > Python Regex Match Before Character AND Ignore White Space

问题描述

I'm trying to write a regex to match part of a string that comes before '/' but also ignores any leading or trailing white space within the match.

So far I've got ^[^\/]* which matches everything before the '/' but I can't figure out how to ignore the white space.

      123 / some text 123

should yield

123

and

     a test / some text 123

should yield

a test

标签: pythonregex

解决方案


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

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

在此处查看现场演示

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

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

推荐阅读