Replace with inline regex variables not working
See original GitHub issueI’m trying to use this line: .pipe(replace(/^(.*)(\r?\n\1)+$/g, '$1'))
, And I’m not getting the expected result. On an example file of:
foo
foo
foo
It should return a file of foo
. Thoughts?
Issue Analytics
- State:
- Created 9 years ago
- Comments:19 (7 by maintainers)
Top Results From Across the Web
javascript - How do you use a variable in a regular expression?
hi i'm trying to use this but not working 'const regex = new RegExp(/(?=.{ \\b${digits}\\b }).*/g);' whereas digits is a numeric variable I'm ......
Read more >sed inline and extended regex does not work together
I am trying to replace an extended regular expression using sed on macOS 10.14.3 (18D109). If I do not use the extended regular...
Read more >Substitutions in Regular Expressions | Microsoft Learn
Substitutions are language elements that are recognized only within replacement patterns. They use a regular expression pattern to define ...
Read more >perlrequick - Perl regular expressions quick start
The literal string in the regex can be replaced by a variable: ... Not all characters can be used 'as is' in a...
Read more >JavaScript String.Replace() Example with RegEx
You're not only restricted to exact characters but patterns and multiple replacements at once. In this article, we've seen how they work ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thanks, I was able to clone that repo and reproduce the issue!
Figured out the problem I think. Sublime must be doing a multiline regex by default (?), or something; but that’s not the case in JS. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#boundaries will tell you that the
^
and&
characters you were using, intending them to mean “start of line” and “end of line”, were actually meaning “start of input” and “end of input”.In order go what you intend, you can either use the multiline flag
m
, or just remove the^
and$
characters (since you’re already checking for line breaks, do you need them?).Does that solve the issue for you @RichardLitt? It worked for me in your repo. (Either
/^(.*)(\r?\n\1)+$/gm
or/(.*)(\r?\n\1)+/g
.)@davidtheclark, thank you for jumping in and helping @RichardLitt figure this one out!