ksh 风格的左右字符串剥离为匹配的表达式?
如何将字符串的左侧部分和右侧部分剥离到 ksh 中的匹配表达式?
例如:(
${name##*/}
${name%/*}
参见 http://www.well. ox.ac.uk/~johnb/comp/unix/ksh.html ksh 示例)。
我似乎无法找到使用 re 模块或 string 模块来执行此操作的简单方法,但我一定错过了一些东西。
How can one strip the left parts and right parts off strings up to a matching expression as in ksh?
For instance:
${name##*/}
${name%/*}
(see http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html for ksh examples).
I can't seem to figure out a simple way of doing this using re module or string module but I must be missing something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Ksh:
Python:
编辑:
要处理模式丢失的情况,如ΤΖΩΤΖIΟΥ所指出的:
Ksh:
Python:
Edit:
To handle the case in which the pattern is missing, as pointed out by ΤΖΩΤΖΙΟΥ:
相当于:
相当于:
Is equivalent to:
Is equivalent to:
“向左剥离”、“向右剥离”等没有特殊状态。一种通用方法是
re.sub
—— 例如,“将所有内容剥离到最后一个”包含斜杠”(ksh 概念化的“向左”):并删除“最后一个斜杠及其后面的所有内容”(每个 ksh“向右”):
这些尽可能匹配,因为
* 是贪婪的;使用
*?
代替非贪婪匹配(“尽可能少”)。There is no special status for "strip to the left", "strip to the right", etc. The one general method is
re.sub
-- for example, to "strip everything up to the last slash included" ("to the left" as ksh conceptualizes it):and to strip "the last slash and everything following" ("to the right" per ksh):
These match as much as possible because the
*
in RE patterns is greedy; use*?
instead for non-greedy matching ("as little as possible") instead.但如果您的目的是将其与路径一起使用,请检查 是否
os.path.dirname
(${name%/*}
) 和os.path.basename
(${name##*/}
) 函数具有您需要的功能。But if your intention is to use it with paths, check whether the
os.path.dirname
(${name%/*}
) andos.path.basename
(${name##*/}
) functions have the functionality you require.