3

I expect to replace "\n\t" with "xxx" in a txt file:

"数字多功能光盘    DVD shùzì"

I do this: str.replace("\n\t","xxx") method matches needed parts but leaves \n part and only replaces \t for 'xxx'.WHY?

why when use crtl+F in VSCOde and it works like charm but in code it doesn't.

Feras Al Sous
  • 1,073
  • 1
  • 12
  • 23
coobit
  • 247
  • 1
  • 6
  • 4
    A newline may be `\r`, `\n`, or `\r\n`. To replace all of these options, use `str.replace(/(?:\r\n?|\n)\t/, "xxx");` – Niet the Dark Absol May 23 '19 at 10:39
  • WTF!? I've spend 2 hours debugging! :( How do you know this? Thanks – coobit May 23 '19 at 10:41
  • 2
    Research and memory? http://www.regular-expressions.info/, http://www.rexegg.com/regex-quickstart.html, https://regex101.com/, https://regexr.com/ – Paul May 23 '19 at 10:44

1 Answers1

1

First of all, str.replace("a","b") only replaces the first occurrence in JavaScript. To replace all of them, you need to use a regex with g modifier. So, you could try str.replace(/\n\t/g,"xxx") first.

Next, why does it work in VSCode? In VSCode regex, \n matches any line break sequence that is selected in the bottom right-hand corner of VSCode app. It works as \R in PCRE, Java, Onigmo, etc. in this case.

As there can be many line ending sequences you may consider "converting" VSCode \n to (?:\r\n|[\r\n\x0B\x0C\x85\u2028\u2029]) that matches any single Unicode line break sequence and use

s = s.replace(/(?:\r\n|[\r\n\x0B\x0C\x85\u2028\u2029])\t/g, '')
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thanks, didn't know that. Why does VScode do so? What is it's logic? – coobit May 23 '19 at 11:43
  • @coobit Probably, the main point was to make the regex more line-oriented, as in Vim. Matching linebreaks in VSCode wth regex has always been a pain. E.g. by default, `[\s\S]` does not match line breaks, it only works when you add `\r` or `\n` there. I think developers tried to make their regex implementation "smarter". In fact, it only confuses users. If your file line endings are CRLF, I'd expect to match them with `\r\n`, but it is not the case :(. – Wiktor Stribiżew May 23 '19 at 11:46