Regex Replace not working

What I’m trying to do:
I would like to use regex replace.

What I’ve tried and what’s not working:
re.split works, while below(replace) line is not working

Code Sample:

# code snippet
 self.k5=re.sub('B|C|Z','_',k1)

The client side implementation of re is limited. A feature request would be a good idea.

A work around would be to do regex on the server.
Or for simple re.sub cases instead use str.replace several times.

So does it mean likewise, most of other libraries/module/functions works properly on server side, in case if it is not working on client side?

Here’s some information about how python works in the browser which should help to explain.

but in short the answer to that is yes. Anything that’s missing on the client should be available on the server.

For what it’s worth for anyone else coming to this before the Skulpt implementation of re.sub has been added, I was able to workaround it by using Javascript’s regular expression mechanism. It wasn’t ideal, but thanks to Anvil’s Javascript integration, it wasn’t hard to get working.

I added this to my native libraries section:

<script>
function re_replace(text, regex, callback)
{
	return text.replace(regex, callback);    
}
</script>

And then in a Python client side module:

def do_replacement(text):
    from anvil.js.window import RegExp
    my_regex = RegExp(regular_expression_goes_here, 'gmi')
    text = anvil.js.call('re_replace', text, my_regex , re_callback)
    return text

Somewhere else in that same module you need the callback function. Note that you have a capture argument for each capture group in your regular expression, so the exact number of arguments to the callback will vary.

def re_callback(matchString, captureOne, captureTwo, position, inputString):
    result = ""

    # do something here to create a result you want put into the string 
    # in place of what the regular expression matched

    return result
1 Like

Nice hack. For the last part you can be even more hacky and stay in python by doing

text = String.prototype.replace.call(text, myregex, replace_text_or_callback)

(Worth noting that the callback can be text instead)

3 Likes

That’s nice! That gets rid of the Javascript function bridge entirely. Thanks!