0

I'd like to remove whole string if the string inside brackets has the word ppm. Simply remove whole bracket if the word ppm inside. How do I do this?

"Menthol(0.3ppm)"   ===> "Menthol"
"Michale(36 years old man)"  ===> "Michale(36 years old man)"
"Good(5%, 5,500ppm)" ===> "Good"

What I tried

str.replace(/\(.+?ppm\)/gim, '')

It works if the word ppm is located in end of brackets, but not working if ppm is located in first or middle of string.

"abcd(333ppm)" ===> "abcd" (OK)
"abcd1234(abc 333ppm)" ===> "abcd1234" (OK)
"abcd(333ppm, 30%)" ===> "abcd(333ppm, 30%)" (NOT OK)
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37
ton1
  • 7,238
  • 18
  • 71
  • 126

5 Answers5

2

You want to use * (match 0 or more characters) instead of + (match 1 or more characters). And to prevent it from matching ( and ), you can use [^\(\)] instead of ..

str.replace(/\([^\(\)]*ppm[^\(\)]*\)/gim, '')
Brandon Gano
  • 6,430
  • 1
  • 25
  • 25
  • What would you want it to return in that scenario? – Brandon Gano Jul 02 '20 at 23:35
  • Try my latest edit. The `[^\(\)]` means "any character that is not (^) a "(" or ")". So the whole regular expression means "'(' followed by any number of characters that aren't '(' or ')' followed by 'ppm' followed by any number of characters that aren't '(' or ')' followed by ')'". – Brandon Gano Jul 03 '20 at 00:10
  • Looks good. [ref](https://regex101.com/r/Eiarhj/3/). – Cary Swoveland Jul 03 '20 at 00:45
  • @Juntae ... does your scenario need a word boundary so that one removes the entire parenthesis in e.g. `def(pig 0.2ppm ABC)` but leaves `def(pig 0.2ppmABC)` untouched? Or should, for the latter example, the entire parenthesis be removed as well? – Peter Seliger Jul 03 '20 at 08:16
2

If there can not be ( or ) between the parenthesis, you could use a negated character class before and after ppm matching any char except the parenthesis or a newline.

\([^()\n]*ppm\b[^()]*\)

Explanation

  • \( Match
  • [^()\n]* Match 0+ times any char except ( ) or newline
  • ppm\b Match ppm and word boundary
  • [^()]* Match 0+ times any char except ( ) or newline
  • \) Match )

Regex demo

[
  "Menthol(0.3ppm)",
  "Michale(36 years old man)",
  "Good(5%, 5,500ppm)"
].forEach(s => console.log(s.replace(/\([^()\n]*ppm\b[^()]*\)/g, '')));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You can use split() and join() if condition is true:

var str="Menthol(0.3ppm)";
var splitStr=str.split("(");
var cleanStr;
if(str.indexOf("ppm")==-1) cleanStr=splitStr.join("(");
else cleanStr=splitStr[0];
console.log('"'+str+'" ===> "'+cleanStr+'"');

look into splitStr: it's an array with two items - [0] before, [1] after -"("...

iAmOren
  • 2,760
  • 2
  • 11
  • 23
0

You can replace matches of the following regular expression with empty strings.

/\((?=[^\)\n]*ppm\b)[^)\n]+\)/

Start your engine!

Javascript's regex engine performs the following operations.

\(          : match '('
(?=         : begin a positive lookahead
  [^\)\n]*  : match any char other than ')' and a line
              terminator 0+ times
  ppm\b     : match 'ppm' followed by a word boundary
)           : end positive lookahead
[^\)\n]+    : match any char other than ')' and a line
              terminator 1+ times
\)          : match ')'
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

A possible and working regex could look like this one ... (/\([^(]*ppm\b[^)]*\)/g).

The pattern reads/matches like this ...

  1. \( ... match a single opening parentheses ... followed by ...
  2. ... [^(]* ... (n)one (or a sequence of) character(s) that is(/are) not a opening parentheses ...
  3. ... followed by the string ppm and a word boundary \b ... followed by ...
  4. ... [^)]* ... (n)one (or a sequence of) character(s) that is(/are) not a closing parentheses ...
  5. ... followed by ... \) ... a closing parentheses.

Starting with the test cases, the OP did provide ...

// OP's test cases
console.log(`
  Menthol(0.3ppm)
  Michale(36 years old man)
  Good(5%, 5,500ppm)

  abcd(333ppm)
  abcd1234(abc 333ppm)
  abcd(333ppm, 30%)
`.replace((/\([^(]*ppm\b[^)]*\)/g), ''));
.as-console-wrapper { min-height: 100%!important; top: 0; }

... one could move on to a more generic solution as it was explicitly ask for ... "How do I remove string in brackets if specific string included with regex?" ...

//  How to escape regular expression special characters using javascript?
//
//  [https://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript/9310752#9310752]
//
function escapeRegExpSearchString(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\\s]/g, '\\$&');
}

function replaceAllParenthesisInStringThatContainSearch(str, search, isCaseSensitive) {
  const flags = `g${ !!isCaseSensitive ? '' : 'i' }`;
  search = escapeRegExpSearchString(search);

  return str.replace(RegExp(`\\([^(]*${ search }\\b[^)]*\\)`, flags), '');
}

const test = `
  abc(cow) and def(pig 0.2_ABCsheep)
  abc(cow) and def(pig 0.2_ABC sheep)

  Menthol(0.3_ABC) Michale(36 years old man)
  Michale(36 years old man) Menthol(0.3_ABC)
  Good(5%, 5,500_ABC)

  abcd(333_ABC) abcd(333_ABC, 30%)
  abcd1234(abc 333_ABC)
  abcd(333_ABC, 30%) abcd(333_ABC)

  abc(cow) and def(pig 0.2_ABC sheep)
`;

console.log(
  replaceAllParenthesisInStringThatContainSearch(test, '_abc')
);

console.log(
  replaceAllParenthesisInStringThatContainSearch(test, '_abc', true)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37