python - 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
解决方案
这有点棘手。您首先从非空白字符开始匹配,然后继续缓慢但肯定地匹配到紧跟可选数量的空格和斜线标记的位置:
\S.*?(?= *\/)
在此处查看现场演示
如果斜线标记可能是输入字符串中的第一个非空白字符,则替换\S
为[^\s\/]
:
[^\s\/].*?(?= *\/)
推荐阅读
- spring - 如何从命令行配置由 GraalVM Native Image 本地编译的 Spring Boot 应用程序的端口?
- cmake - 缺少的变量是:CMAKE_CUDA_COMPILE_WHOLE_COMPILATION
- android - 如何仅在按下按钮时显示片段?
- css - 列内的中心按钮
- java - 在 Android 的 ListView 上显示 Css 样式的 Html 数据
- spring - 模仿 `reduceWhile` 之类的运算符
- android - 在 viewpager2 中禁用动画
- django - 使用用户以外的模型授权客户端
- sql - 如何从 oracle 获得最接近的值
- r - R - 在几个动作上运行一个循环