开发者

Python regular expression problem

开发者 https://www.devze.com 2023-01-21 15:54 出处:网络
I need to do something in regex but I\'m really not good at it, long time didn\'t do that . /a/c/a.doc

I need to do something in regex but I'm really not good at it, long time didn't do that .

/a/c/a.doc
开发者_Python百科

I need to change it to

\\a\\c\\a.doc

Please trying to do it by using regular expression in Python.


I'm entirely in favor of helping user483144 distinguish "solution" from "regular expression", as the previous two answerers have already done. It occurs to me, moreover, that os.path.normpath() http://docs.python.org/library/os.path.html might be what he's really after.


why do you think you every solution to your problem needs regular expression??

>>> s="/a/c/a.doc"
>>> '\\'.join(s.split("/"))
'\\a\\c\\a.doc'

By the way, if you are going to change path separators, you may just as well use os.path.join

eg

mypath = os.path.join("C:\\","dir","dir1")

Python will choose the correct slash for you. Also, check out os.sep if you are interested.


You can do it without regular expressions:

x = '/a/c/a.doc'
x = x.replace('/',r'\\')

But if you really want to use re:

x = re.sub('/', r'\\', x )


\\ is means "\\" or r"\\" ?

re.sub(r'/', r'\\', 'a/b/c')

use r'....' alwayse when you use regular expression.


'\\\'.join(r'/a/c/a.doc'.split("/"))
0

精彩评论

暂无评论...
验证码 换一张
取 消