[英]Python Regex Match Before Character AND Ignore White Space
我正在尝试编写一个正则表达式来匹配'/'之前的字符串的一部分,但也忽略了匹配中的任何前导或尾随空格。
到目前为止,我有^[^\\/]*
匹配'/'之前的所有内容,但我无法弄清楚如何忽略空格。
123 / some text 123
应该屈服
123
和
a test / some text 123
应该屈服
a test
您可能希望探索此表达式:
^(.*?)(\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中可视化表达式:
对于所需输出之前的空格,我们可以简单地添加一个带有负向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(?=\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
懒得匹配任何东西 ( .*
),同时确保它不以空格开头或结尾( \\S
) (?=\\s*\\/)
表示可能的匹配必须后跟/
符号或空格+ a /
。 你可以在没有正则表达式的情况下完成它
my_string = " 123 / some text 123"
match = my_string.split("/")[0].strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.