0

I've done some research, like 'How do you use a variable in a regular expression?' but no luck.

Here is the given input

const input = 'abc $apple 123 apple $banana'

Each variable has its own value.

Currently I'm able to query all variables from the given string using

const variables = input.match(/([$]\w+)/g)

Replacement through looping the variables array with the following codes is not successful

const r = `/(\$${variable})/`;
const target = new RegExp(r, 'gi');
input.replace(target, value);

However, without using the variable, it will be executed,

const target = new RegExp(/(\$apple)/, 'gi');
input.replace(target, value);

I also changed the variable flag from $ to % or #, and it works with the following codes,

// const target = new RegExp(`%{variable}`, 'gi');
// const target = new RegExp(`#{variable}`, 'gi');
input.replace(target, value);

How to match the $ symbol with variable in this case?

Mark
  • 169
  • 1
  • 8

3 Answers3

1

I have been using regular expressions just about everyday for almost a year now. I'll post my thoughts and just say:

Regular Expressions are most useful at finding parts of a text or data file.

If there is a text-file that contains the word "apple" or some derivative there-in, regular-expressions can be a great tool. I use them everyday for parsing HTML content, as I write foreign-news translations (based in HTML).

I believe the code that was posted was in JavaScript (because I saw the replace(//,"gi") function which is what I know is used in that scripting language. I use Java's java.util.regex package myself, and the syntax is just slightly different.

If all you want to do is put a "place-holder" inside of a String - this code could work, I guess - but again, understanding why "regular-expressions" are necessary seems like the real question. In this example, I have used the ampersand ('&') as the placeholder - since I know for a fact it is not one of the "reserved key words" used by (most, but not necessarily all of) the Regular Expression Compiler and Processor.

var s1 = "&VAR1"; // Un-used variable - leaving it here for show!
var myString = "An example text-string with &VAR1, a particular kind of fruit.";
myString.replace(/&VAR1/gi, "apple");

If you want a great way to practice with Regular-Expressions, go to this web-site and play around with them:

https://regexr.com/

Here are the rules for "reserved key symbols" of RegEx Patterns (Copied from that Site):

The following character have special meaning, and should be preceded by a \ (backslash) to represent a literal character: +*?^$.[]{}()|/

Within a character set, only \, -, and ] need to be escaped.

Also, sort of "most importantly" - Regular Expressions are "compiled" in Java. I'm not exactly sure about how they work in Java-Script - but there is no such concept as a "Variable" in the Compiled-Expression Part of a Regular Expression - just in the text and data it analyzes. What that means is - if you want to change what you are searching for in a particular piece of Text or Data in Java, you must re-compile your expression using:

Pattern p = Pattern.compile(regExString, flags);

There is not an easy way to "dynamically change" particular values of text in the expression. The amount of complexity it would add would be astronomical, and the value, minimal. Instead, just compile another expression in your code, and search again. Another option is to better undestand things like .* .+ .*? .+? and even (.*) (.+) (.*?) (.+?) so that things that change, do change, and things that don't change, won't!

For instance if you used this pattern to match different-variables:

input.replace(/&VAR.*VAREND/gi, "apple");

All of your variables could be identified by the re-used pattern: "&VAR-stuff-VAREND" but this is just one of millions of ways to change your idea - skin the cat.

  • Even @Sphinx replied faster, but you did point out several valuable suggestions, upvote! – Mark Oct 12 '18 at 17:21
1

If understand correctly, uses (\\$${variable}).

You can check below Fiddle, if only one slash, it will cause RegExp is /($apple)/gi (the slash and the following character are escaped: \$ => $), but $ indicates the end of string in Regex if not escaped.

So the solution is add another slash.

Like below demo:

const input = 'abc $apple 123 apple $banana'
let variable = 'apple'
let value = '#test#'
const r = `(\\$${variable})`;
const target = new RegExp(r, 'gi');
console.log('template literals', r, `(\$${variable})`)
console.log('regex:', target, new RegExp(`(\$${variable})`, 'gi'))
console.log(input.replace(target, value))
Sphinx
  • 10,519
  • 2
  • 27
  • 45
1

Using a replace callback function you can avoid building a separate regex for each variable and replace them all at once:

const input = 'abc $apple 123 apple $banana'

const vars = {
   apple: 'Apfel',
   banana: 'Banane'
}

let result = input.replace(/\$(\w+)/g, (_, v) => vars[v])

console.log(result)

This won't work if apple and banana were local variables though, but using locals is a bad idea anyways.

georg
  • 211,518
  • 52
  • 313
  • 390