Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

150
Views
Why are these two regular expressions not equivalent?

I was trying to split a text with unknown line delimiters into single lines (ignoring blank lines). The first regex that I tried was /(\r|\n)+/m but that didn't work; that splits "a\r\nb" into [ "a", "\n", "b" ] instead of the expected [ "a", "b" ]. I already found out /[\r\n]+/m does what I want it to, but the two regexes seem equivalent to me (if the capture group itself isn't important). What am I missing?

console.log("a\r\nb".split(/(\r|\n)+/m));
console.log("a\r\nb".split(/[\r\n]+/m));

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The two regex patterns do match the same thing. The actual difference is the presence of the capture group in the first version. If we add a capture group to the second version, the splitting behavior is identical:

console.log("a\r\nb".split(/(\r|\n)+/m));
console.log("a\r\nb".split(/([\r\n])+/m));

Note that the behavior of split() is such that the contents of the capture group are included in the split output. As an alternative, you could have made the first capture group non capturing, and then again the splitting behavior would be the same:

console.log("a\r\nb".split(/(?:\r|\n)+/m));
console.log("a\r\nb".split(/[\r\n]+/m));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!