python重新删除lin中<(独占)和last/(包含)之间的文本

2024-04-20 12:43:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本来编辑.cpp和h文件库。由于unity3d和iOS本机插件的变幻莫测,我不得不完全扁平化它的目录结构。所以我必须检查所有的文件并改变这个。。(例如)

   #include <Box2D/Dynamics/Joints/b2DistanceJoint.h>

对这个。。你知道吗

   #include <b2DistanceJoint.h>

因此,我需要一个regex命令来删除<;和last/之间的一行中的任何文本,并删除last/。如果没有/则什么也不会发生(尽管如果需要,我可以使用if语句)


Tags: 文件目录脚本插件编辑includeunity3d结构
3条回答

试试这个:

code = '''#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>
#include <Box2D/Dynamics/Joints/xyz.h> #include <Box2D/Dynamics/Joints/xyz.h>
#include <pqr.h>'''

code = re.sub("(?:(?<=^)|(?<=[\n\r]))#include\s+<[^>]*/", "#include <", code)

(?:(?<=^)|(?<=[\n\r]))确保#include仅位于行的开头。这样它就不会碰到另一个#include

正则表达式解释:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    ^                        the beginning of the string
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    [\n\r]                   any character of: '\n' (newline), '\r'
                             (carriage return)
--------------------------------------------------------------------------------
  )                        end of look-behind

如果需要,可以不使用regex解决这个问题,在第一个<字符和最后一个/字符之间进行切片:

>>>s = "#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>"
>>>s[:s.find('<')+1] + s[s.rfind('/')+1:]
'#include <b2DistanceJoint.h>'

当然,可能您遇到了一个没有/的行,在这种情况下,我假设您希望保持它不变,因此可以添加一个if来检查:

>>>s = "#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>"
>>>if s.rfind('/') >= 0:
>>>    s = s[:s.find('<')+1] + s[s.rfind('/')+1:]
'#include <b2DistanceJoint.h>'

使用这个正则表达式<.*\/.*\/

REgex Demo

在这里验证输出:IDEONE

代码:

import re

text = """#include <Box2D/Dynamics/Joints/b2DistanceJoint.h>"""
#print text
print re.sub(r'<.*\/.*\/','<',text)

输出:

#include <b2DistanceJoint.h>

相关问题 更多 >