0

I'm trying to redact some information using regular expression in Javascript. With the below regex I'm able to replace the part of the values.

EDIT

Original String:

mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA -p -e 'SELECT

Expression:

text.replace(/(.*--user=)(\s*)([^]*)/, '$1XX$2')

Output:

mysql --user=XX

However, I would like the output to be:

mysql --user=XX --host=XXXXXX --database=XXXX -p -e 'SELECT

Could someone help me with the regular expression to achieve this?

3
  • consider using a cli parser Commented Aug 19, 2021 at 17:37
  • or use $3.... Commented Aug 19, 2021 at 17:37
  • how do you determine how many X you need to have? Commented Aug 19, 2021 at 17:57

4 Answers 4

2

If the format stays the same with the single space between the key-value parts, the keys start with -- and there is XX in the replacement, you could match the pattern and capture the key value parts in group 1.

\bmysql (--\w+=\w+(?: --\w+=\w+)*)

regex demo

In the replacement, split on a space and replace the last part after the = with XX

const s = "mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA";
const regex = /\bmysql (--[^\s=]+=[^\s=]+(?: --[^\s=]+=[^\s=]+)*)/;
const result = s.replace(
  regex,
  (_, g1) => "mysql " + g1
  .split(' ')
  .map(s => s.split('=')[0] + "=XX")
  .join(' ')
);
console.log(result);


An example using an infinite quantifier in the lookbehind

(note that if this is for security, replacing each char with a single X can give away a hint about the length of the string)

(?<=\bmysql(?: --[^\s=]+=[^\s=]+)* --[^\s=]+=)[^\s=]+

Regex demo

const s = "mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA";
const regex = /(?<=\bmysql(?: --[^\s=]+=[^\s=]+)* --[^\s=]+=[^\s=]*)[^\s=]/g;
const result = s.replace(regex, "X");

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

A considerably simpler solution to achieve what you want with just one Regex replace is the following pattern:

(?<=--[a-zA-Z0-9]*=)([^ ]*)

const pattern = /(?<=--[a-zA-Z0-9]*=)([^ ]*)/g
const command= "mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA"

console.log(command.replace(pattern, "XX"))

Comments

0

If the number of X doesn't matter, then this is short and sweet:

const str = 'mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA';
const newStr = str.replace(/(?<=--\w+=)\w+/g, 'XX');
console.log(newStr);

Comments

0

If you want number of X to match number of characters in the values:

const text = 'mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA';
const regExp = /(?<= --\w+?=[^ ]*)[^ ]/g;

console.log(text.replace(regExp, 'X'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.