tags:

views:

87

answers:

5

Hi, 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 change it to

\\a\\c\\a.doc

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

+1  A: 

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 )
Graeme Perrow
You can use a raw string to make this cleaner.
Swiss
@Swiss Thanks for the suggestion - I fixed my answer.
Graeme Perrow
+2  A: 

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.

ghostdog74
it does not seem that the original poster believes that every solution needs regular expression.
akonsu
@akonsu, almost all his previous posts are about regex.
ghostdog74
+3  A: 

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.

Cameron Laird
A: 

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

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

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

guilin 桂林
A: 

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

ShyamLovesToCode