Question

I have written the following code to match a service name in my property file :-

service = properties.match(/^com\.google\.([#{serviceName}]+)\.public$/)

This code works fine when I give any serviceName but fails if the serviceName has a - in between

Eg - common-api

Error:

empty range in char class: /^com\.google\.([common-api]+)\.public$/ (SyntaxError)

Any idea how can i escape the whole string from regex evaluation?

Was it helpful?

Solution

You probably want Regexp.escape:

service = properties.match(/^com\.google\.(#{Regexp.escape(serviceName)})\.public$/)

Additionally, you had surrounded your inclusion of serviceName with a [...]+, which means more than one character from this list of characters in [...].

E.g. This regexp [commonapi]+ accepts moconaipimdconn, or indeed any length string that contained some characters from the service name you actually wanted to capture.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top