Home > Blockchain >  Match whole lines but remove specific word/expression directly from match
Match whole lines but remove specific word/expression directly from match

Time:03-07

I have a some multi-lines files that have strange format. It looks a little like this:

line 1: text1 0.2348953147573326nope text2Text3 text4\n
line 2: blabla-blabla\n
[...]

How can I match whole lines of data but remove those "0.2348953147573326" (random float values glued to some words) directly from the regex match? The expected regex match would be like:

text1 nope text2Text3 text4\n
blabla-blabla\n[...]

CodePudding user response:

If the number you want to remove is always a decimal, this would do the job:

let str = "text1 0.2348953147573326nope text2Text3 text4\n blabla-blabla\n[...]";
console.log(str.replace(/\d \.\d /, ""));

Expression explained:

  • \d : matches a digit (0-9) 1 or more times
  • \.: matches a dot character (.)
  • \d: as said before, matches a digit (0-9) 1 or more times

CodePudding user response:

Ok, I figured out solution in terms of fit regex pattern. For me worked:

(^.  (?=\d \.\d )|(?<=\d \.\d )\D. $)|^((?!\d \.\d ).)*$
  • (^. (?=\d \.\d ): match stuff before excluded expression (in my example it is float value),
  • (?<=\d \.\d )\D. $): match stuff after excluded expression,
  • ^((?!\d \.\d ).)*$: match lines that doesn't contain excluded expression
  • Related