Mahendran V M
Mahendran V M

Reputation: 3496

How to use regex to remove the spaces between two rows?

My Input file like this

Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,

 22-02-2017,1-2,10,,,,
 22-02-2017,2-3,11,,,,

 22-02-2017,4-6,10,,,,
 22-02-2017,5-8,11,,,,

I need to regex to achive below expected output:

Header1,,,,,,,,,,,
c1 , c2 , c3 ,,,,
22-02-2017,1-2,10,,,,
22-02-2017,2-3,11,,,,
22-02-2017,4-6,10,,,,
22-02-2017,5-8,11,,,,

I trying this regex for search \s\n in REplaceTExt and replacement value is \n.

After Replace text output content like below.,

Header1,,,,,,,,,,,c1 , c2 , c3 ,,,,22-02-2017,1-2,10,,,,22-02-2017,2-3,11,,,,22-02-2017,4-6,10,,,,

But my regex worked perfectly in regexr website.

http://regexr.com/3fbse

Is there is any other regex to search empty rows and combine rows before and after of empty rows?

Upvotes: 1

Views: 987

Answers (3)

mickmackusa
mickmackusa

Reputation: 48001

Sahil's solution is not as refined as it could be:

You can match with this pattern: \n+\s and replace with \n. Demo

This will provide the same result with fewer steps.

The points to keep in mind with this very simple task is that using "alternatives" (pipes |) adds steps to your pattern and should be avoided when possible.

When alternatives are necessary, order the alternatives from shortest to longest -- this will provide greater efficiency.

Lastly, do not repeat characters in your pattern, use quantifiers -- this again improves performance. When comparing \n\n\s|\n\s versus \n{2}\s|\n\s, the latter will outperform the former simply by using the {2} quantifier.


Probably the best advice would be to read your file with file() (which delivers an array of lines) and set the desired flags.

$array = file('yourfile.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

This prevents needing to perform the extra preparation step with regex or a replacing string function.

fgetcsv() is a great companion for this approach.

Upvotes: 1

m87
m87

Reputation: 4513

Yes, you could also try something like the following to search for empty rows and remove them.

regex search >> /\n+/g
replace with >> \n

see demo

Upvotes: 2

Sahil Gulati
Sahil Gulati

Reputation: 15141

Search: \n\n\s|\n\s

Replace: \n

Regex Demo

Upvotes: 1

Related Questions