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

。_饼干妹妹 提交于 2019-12-11 09:32:49

问题


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?


回答1:


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

Replace: \n

Regex Demo




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/42384143/how-to-use-regex-to-remove-the-spaces-between-two-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!