I am new to regular expressions, but I do not get why this is not working
:

import re
inputstr = "HI\n//asgwrg\nasdg"
re.sub("\/\/(.*)(\n)", "\n", inputstr)

I am trying to substitute everything between "//" and newline with newline. Can someone tell me whats wrong?

I am using python 3.1

Recommended Answers

All 3 Replies

I am new to regular expressions, but I do not get why this is not working
:

import re
inputstr = "HI\n//asgwrg\nasdg"
re.sub("\/\/(.*)(\n)", "\n", inputstr)

I am trying to substitute everything between "//" and newline with newline. Can someone tell me whats wrong?

I am using python 3.1

What do you mean by, "it's not working" ? It works fine for me:

>>> import re
>>> inputstr = "HI\n//asgwrg\nasdg"
>>> re.sub("\/\/(.*)(\n)", "\n", inputstr)
'HI\n\nasdg'
>>>

More details please on what doesn't work.

import os
import re
inputstr = "HI\n//asgwrg\nasdg"
print(inputstr)
re.sub("\/\/(.*)(\n)*", "|REP|\n", inputstr)
print("\nNEW:\n",inputstr)

Ok thats my hole program so far, and I get:

HI
//asgwrg
asdg

NEW:
 HI
//asgwrg
asdg

when I run it

That's because you're printing inputstr again... The re.sub method isn't an "in-place" transformation. You actually need to save the output like so:

import os
import re

inputstr = "HI\n//asgwrg\nasdg"
print(inputstr)

outputstr = re.sub("\/\/(.*)(\n)*", "|REP|\n", inputstr)
print("\nNEW:\n",outputstr)

Here's my output:

HI
//asgwrg
asdg

NEW:
HI
|REP|
asdg
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.