TransWikia.com

How to do a regex negative lookahead in a ee.String.replace()?

Geographic Information Systems Asked on August 12, 2021

I thought this would work, but it doesn’t:

var someText = ee.String("1_2_text").replace('(?:d_)*(?!d)','').aside(print)

I would expect 1_2_ to be matched and replaced with nothing. Instead I am getting the following error:

String (Error)
String.replace: Invalid regular expression: '(?:d_)*(?!d)' (invalid perl operator: (?!).

which is very confusing, since I don’t even use Perl. I guess Earth Engine uses Perl behind the scenes, even though this isn’t documented anywhere, but anyway, Perl supports negative lookaheads.

One Answer

It's not exactly Perl, it's that the lookahead operator you're trying to use is part of an extended regex expression language commonly referred to as PERL-re. Earth Engine uses RE2 instead (in which that operator isn't supported).

If you're just looking to match and replace any leading numeric+underscore prefixes, I think this should get you there:

.replace('^([0-9]+_)*', '')

Correct answer by Noel Gorelick on August 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP