(Regular Expressions) 2Liner→1Liner

2019-08-05 11:06发布

Thank you in advance and sorry for the bad english!

I want

'Odd rows' 'CRLF' 'Even rows' CRLF' → 'Odd rows' ',' 'Even rows' 'CRLF'

Example Input:

  0
SECTION
  2
HEADER

Desired Output:

  0,SECTION
  2,HEADER

What I have tried:

Find: (.*)\n(.*)\n
Replace: $1,$2\n

I want ー Easy to see dxf

标签: regex dxf
4条回答
爷、活的狠高调
2楼-- · 2019-08-05 11:54

DXF file ok

ODD line abc...

(AWK)

NR%2!=0{L1=$0}
NR%2==0{print L1 "," $0;L1=""}
查看更多
对你真心纯属浪费
3楼-- · 2019-08-05 11:55

you should match enter and space also, because there may be multiple spaces and new line available in string try this regex-

"0\nSECTION\n 2\nHEADER".replace(/([\d]+)([\s\n]+)([^\d\s\n]*)/g,"$1,$3")

var myStr = `  0
SECTION
  2
HEADER`;

var output = myStr.replace(/([\d]+)([\s\n]+)([^\d\s\n]*)/g,"$1,$3");
console.log(output);

查看更多
Viruses.
4楼-- · 2019-08-05 11:58

For you example data you could capture one or more digits in capturing group 1 followed by matching a newline.

In the replacement use group 1 followed by a comma.

Match

(\d+)(?:r?\n|\r)

Regex demo

Replace

$1,

查看更多
5楼-- · 2019-08-05 11:58

. matches a newline the same as it matches any other characer, so the first .* is going to gobble up the whole string and leave nothing left.

Instead, use a character group that excludes \n. Also, it's not clear whether your final line terminates with a \n or not, so the Regex should handle for that:

Find

([^\n]*)\n([^\n]*)(\n|$)

Replace

$1,$2$3

Breakdown:

  • ([^\n]*) - 0 or more characters that are not \n
  • \n
  • ([^\n]*)
  • (\n|$) - \n or end of string
查看更多
登录 后发表回答