Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1063
  • Last Modified:

Python, regex, replace characters not between quotes

Hey,

I'm trying to create an (unusual?) regex statement using python str.replace or re.

Simply, I want to replace every character or number NOT between quotes in a string. I can do it using a "for i in " loop and just checking every character, but (I am assuming) regex would be a million times faster :-)  

I.e.

var = 'This is not in quotes "while this is" but this isnt'
var = <magic>
print var
cccc cc cccc cc cccccc while this is ccc cccc cccc

or

var = 'This num is 384 "but this num is 223" and neither is 444'
var = <magic>
print var
cccc ccc cc ### but this num is 223 ccc ccccccc cc ###


--- appended ---

I came up with this so far..

import re
pattern = r"'([^'\\]*(?:\\.[^'\\]*)*)'"
var = "word is word word 'This is a test' is crap"
m = re.search(pattern, var)
replaced_var = re.sub(r'[a-zA-Z]', "c", var)
var = replaced_var[:(m.start())] + var[(m.start()+1):(m.end()-1)] + replaced_var[(m.end()):]
print var

[OUTPUT]
cccc cc cccc cccc This is a test cc cccc


IS THERE A WAY to get this to work with multiple quoted areas in a string. I.e. maybe using regex groups such that...

var = replaced_var[:<group 0 m.start] + var[<1st quoted text>] + replaced_var[<group 0 m.end>]

var =  var + replaced_var[:<group 1 m.start] + var[<2nd quoted text>] + replaced_var[<group 1 m.end>]

var = var + <etc>

Thanks!
0
Mike R.
Asked:
Mike R.
  • 4
  • 2
  • 2
  • +3
1 Solution
 
oheilCommented:
What is the expected result, when you have odd number of " ?
Like:

abc"def"ghi"jkl

What would be the desired result?

Oli
0
 
peprCommented:
There is at least one more problem. The quoted string may contain \" -- i.e. escaped quote.
0
 
oheilCommented:
Yes, maybe, if escaping of double-quotes should be also possible.

Are we talking only about double-quotes <"> (like in the examples above) or should single-quotes <'> be equivalent.

I am thinking of a recursive solution, so the problem of odd number of " came into mind.

Oli
0
Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

 
gelonidaCommented:
agree with pepr.
the escaped quotes if they can exist in your context would complicate the situation a bit.

Next question as I don't know what you are parsing.

can you have multi-line entries, where the quote pairs stretch over multiple lines?

Example:
 'This num is
384 "but this num is
223" and neither is 444'

Depending on your answers it might be easiest to split your problem into two parts.
the first part would be an iterator yielding
a tuple (unquoted_part, quoted_part)
and then you can replace in the part where you'd like to with a classical regexp

This is more manual, but might be better to understand, debug and maintain and will probably not be that much slower.
0
 
farzanjCommented:
Regular expression is not going to be faster than a loop at all.  A lot of Regex will be much slower indeed.  They are faster in terms of coding time, making your time of development faster and shorter not the speed of execution faster.
0
 
Mike R.Author Commented:
Thanks for the input. So, this is actually part of a script to "user-friendly-ize" input for users who DON'T know regex.

SHORT ANSWERS:
oheil: It checks for matching quotes before processing. If unmatched quotes are found, it just halts.

pepr: Escaped chars won't be allowed ( \ should be ignored)

oheil: I may restrict it to tics actually ``. I haven't decided.

LONG ANSWERS:
Actually, (because maybe you have a better solution altogether) I'm writing a function to check the format of user input without needing to write a bunch of matches into the calling script...i.e. ...

The function user can make a call defining the exact format of the input with wildcards. The things in quotes need to match the input EXACTLY. The other chars represent different variations of wildcards (I.e. one for char only, one for num only, one for anything...etc)

format_var = " '/dev/disk/by-'..'/scsi-'* "
inputf(format_var)

meaning the user must input a string ...
/dev/disk/by-<any two chars>/scsi-<any number of chars>

I.e.   /dev/disk/by-id/scsi-2133213213213213213213213213
...is good but...

/dev/dsk/by-id/scsi-2133213213213213213213213213
or
/dev/dIsk/by-id/scsi-2133213213213213213213213213
or
./by-id/scsi-2133213213213213213213213213

...will all fail as not matching the format_var string style.

Does this make sense. Is there a module that already does this? I didn't find one :-)
0
 
Sharon SethCommented:
Dosen't fnmatch do it already?
0
 
peprCommented:
@farzanj: > Regular expression is not going to be faster than a loop at all.

Regular expressions usually are faster. But I agree that loop may be easier in this case.

@rightmirem: If using regular expressions in Python, I suggest to prefer the compiled form almost always.
0
 
oheilCommented:
This is what I would do:

Splitting the input string into an array of parts. Each part with even index is outside single quotes (') and odd index is inside single quotes. The parts can be empty. This is the code:

import re

input = "abc''def'ghi'123'jkl'456"

p = re.compile("(.*?)('.*?')(.*)")

input_list = ["","","",input]

print "Input:"
print input_list[3]

result_list = []
loop=1
while len(input_list[0])==0 and len(input_list[3]) > 0 :
   input_list = p.split(input_list[3])
   if len(input_list[0]) > 0 :
      result_list.append(input_list[0])
      loop=0
   else :
      result_list.append(input_list[1])
      result_list.append(input_list[2])

print
print "Result:"
i=0
while i < len(result_list) :
   print result_list[i]
   i += 1

Open in new window


Oli
0
 
oheilCommented:
Per definition, if the number of single quotes is odd, than the last part is not inside quotes but contains on quote.

You may check with the example string
input = "abc'def'ghi'123'jkl'456"

Open in new window


Oli
0
 
gelonidaCommented:
Who's choosing the format of format var.
 
Why don't you use a regexp for it?
0
 
Mike R.Author Commented:
Worked beautifully actually. Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

  • 4
  • 2
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now