【发布时间】:2026-01-26 13:25:01
【问题描述】:
我正在尝试编写一个正则表达式来匹配 '/' 之前的字符串的一部分,但同时忽略匹配中的任何前导或尾随空格。
到目前为止,我有 ^[^\/]* 匹配“/”之前的所有内容,但我不知道如何忽略空格。
123 / some text 123
应该让步
123
和
a test / some text 123
应该让步
a test
【问题讨论】:
我正在尝试编写一个正则表达式来匹配 '/' 之前的字符串的一部分,但同时忽略匹配中的任何前导或尾随空格。
到目前为止,我有 ^[^\/]* 匹配“/”之前的所有内容,但我不知道如何忽略空格。
123 / some text 123
应该让步
123
和
a test / some text 123
应该让步
a test
【问题讨论】:
这有点棘手。您首先从非空白字符开始匹配,然后继续缓慢但肯定地匹配到紧跟可选数量的空格和斜线标记的位置:
\S.*?(?= *\/)
如果斜线标记可能是输入字符串中的第一个非空白字符,则将\S 替换为[^\s\/]:
[^\s\/].*?(?= *\/)
【讨论】:
这个表达式是你可能想要探索的:
^(.*?)(\s+\/.*)$
在这里,我们有两个捕获组,第一个收集您想要的输出,第二个是您不想要的模式,以开始和结束字符为界,为了安全起见,如果您愿意,可以将其删除:
(.*?)(\s+\/.*)
# 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.
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+\/.*)$
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);
【讨论】:
\s+ 要求在 / 之前有一个空格。 \s* 不会,因此即使没有空格,正则表达式也会匹配,例如 abc/。问题中的所有示例在 / 之前都有一个空格,所以(在没有特定要求的情况下)我认为\s+ 在这里是正确。
? 是其中的一部分。然后看起来他们之间没有区别,除了可能在效率上。
这是一个可能的解决方案
正则表达式
(?<!\/)\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'
简短说明
(?<!\/) 表示在可能的匹配之前不能有 / 符号。\S.*\S 延迟匹配 anything (.*),同时确保它不以空格开头或结尾 (\S)(?=\s*\/) 表示可能的匹配必须后跟 / 符号或空格 + /。【讨论】:
你可以不用正则表达式
my_string = " 123 / some text 123"
match = my_string.split("/")[0].strip()
【讨论】:
my_string = " / something"。这里不同的方法各不相同:您的解决方案返回一个空字符串,而正则表达式返回 None。