简体   繁体   中英

Put all occurences in the String in quotes using regex in python

I hava a long string were I can find something like this data() { <some data which is always different here> } I want to put all occurences in quotes. This is what I'm doing but it has no effect:

string = re.sub(r'data \(\) {(.*)}', r'"/1"', string)

I suppose there should be something different between curly brackets but I have no idea what...

@EDIT I realized my String look like this:

data() {
  <some white spaces> here is text
<some white spaces> }

Whitespace matters, the direction of slashes matters (thanks Wiktor, I overlooked that before) and that quantifier should probably be lazy. Also, if there are newlines within your text, you need to allow for that

string = re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string)

Testing it on your sample text:

In [4]: string = """data() {
   ...:   <some white spaces> here is text
   ...: <some white spaces> }"""

In [5]: print(re.sub(r'(?s)data\(\) {(.*?)}', r'"\1"', string))
"
  <some white spaces> here is text
<some white spaces> "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM