Does NJS support reg ex positive look behinds?

Dmitry Volyntsev xeioex at nginx.com
Fri Jan 31 13:02:11 UTC 2020



On 31.01.2020 12:06, Shani Ranasinghe wrote:
> Hi,
> I would like to know if njs supports regex positive look behinds.
> I have written a script in perl and would like to convert it to njs. The 
> reg ex I have in perl is 
> "((?<=[a-z])(?=[A-Z])(?!ID)(?!^Open$)|(?<=ABC)|(?<=API)(?=[A-Z])|(?=Connect))"
> This would give the following outputs.
> 
> *Inputs and expected outputs* are *listed below* in the format *Input -> 
> Expected Output*
> 
>  1.
> 
>     InstallAndSetup -> install-and-setup
> 
>  2.
> 
>     DeployingABCDefGhijk -> deploying-abc-def-ghijk (assuming abc is a
>     noun that is frequently used)
> 
>  3. OpenIDConnect -> openid-connect
>  4. OAuth2Scopes->oauth2-scopes
>  5. APISecurity -> api-security
> 
> I would like to know if there's a way to achieve this with njs?
> 
> Thank you in advance.
> Regards,
> Shani.


Hi Shani,

njs uses libpcre for regexp which supports positive look behinds (but 
only fixed length lookbehind)

compare (using njs CLI, which is installed with official njs packet)

: >> (new RegExp("(?<=[A-Z]+)(abc)")).exec('Aabc')
: Thrown:
: SyntaxError: pcre_compile("(?<=[A-Z]+)(abc)") failed: lookbehind 
assertion is not fixed length at ")(abc)"
:     at RegExp.prototype.constructor (native)
:     at main (native)

with

: >> (new RegExp("(?<=[A-Z])(abc)")).exec('Aabc')
: [
:  'abc',
:  'abc'
: ]

> I would like to know if there's a way to achieve this with njs?

Almost everything is possible, the question is what you are trying to do.
Converting CamelCase to kebab-case?

You may want to use something like this:

: >> function camelCaseToDash(s) { return 
s.replace(/([A-Za-z0-9])([A-Z][a-z])/g, '$1-$2').toLowerCase() }
: undefined
: >> function normalize(s) {return s.replace(/(API|OAuth|ABC)/g, 
(m)=>`${m[0]}${m.substring(1).toLowerCase()}`)}
: undefined
: >> ['InstallAndSetup', 'DeployingABCDefGhijk', 'OpenIDConnect', 
'OAuth2Scopes',
: 'APISecurity'].map(normalize).map(camelCaseToDash)
: [
:  'install-and-setup',
:  'deploying-abc-def-ghijk',
:  'openid-connect',
:  'oauth2-scopes',
:  'api-security'
: ]

> 
> _______________________________________________
> nginx-devel mailing list
> nginx-devel at nginx.org
> http://mailman.nginx.org/mailman/listinfo/nginx-devel
> 


More information about the nginx-devel mailing list