8

Say I have text like the following text selected with the cursor:

This is a test. 
This 
is a test.

This is a test. 
This is a 
test.

I would like to transform it into:

This is a test. This is a test

This is a test. This is a test

In other words, I would like to replace single line breaks by spaces, leaving empty lines alone.

I thought something like the following would work:

RemoveSingleLineBreaks()
{
  ClipSaved := ClipboardAll
  Clipboard =
  send ^c
  Clipboard := RegExReplace(Clipboard, "([^(\R)])(\R)([^(\R)])", "$1$3")    
  send ^v
  Clipboard := ClipSaved
  ClipSaved = 
}

But it doesn't. If I apply it to the text above, it yields:

This is a test. This is a test.
This is a test. This is a test.

which also removed the "empty line" in the middle. This is not what I want.

To clarify: By an empty line I mean any line with "white" characters (e.g. tabs or white spaces)

Any thoughts how to do this?

4

4 回答 4

6
RegExReplace(Clipboard, "([^\r\n])\R(?=[^\r\n])", "$1$2")

假设新行标记在末尾包含 aCR或 a (例如, , , ),这将去除单个换行符。它不将空格视为空。LFCRLFCR+LFLF+CR

您的主要问题是使用\R

字符类中的 \R 仅仅是字母“R” [来源]

解决方法是直接使用CRandLF字符。


澄清一下:空行是指任何带有“白色”字符的行(例如制表符或空格)

RegExReplace(Clipboard, "(\S.*?)\R(?=.*?\S)", "$1")

这与上面的相同,但将空格视为空。它之所以有效,是因为它以非贪婪方式接受除换行符 ( *?) 之外的所有字符,直到换行符前后的第一个非空白字符,因为.默认情况下不匹配换行符。

前瞻用于避免“吃掉”(匹配)下一个字符,该字符可能会在单字符行上中断。请注意,由于它不匹配,因此它不会被替换,我们可以将它排除在替换字符串之外。因为 PCRE 不支持可变长度的lookbehinds,所以不能使用lookbehinds,所以这里使用普通的捕获组和反向引用。


我想用空格替换单个换行符,只留下空行。

如果你想用空格替换换行符,这样更合适:

RegExReplace(Clipboard, "(\S.*?)\R(?=.*?\S)", "$1 ")

这将用空格替换单个换行符。


如果你想使用lookbehinds和lookaheads:


去除单个换行符:

RegExReplace(Clipboard, "(?<=[^\r\n\t ][^\r\n])\R(?=[^\r\n][^\r\n\t ])", "")


用空格替换单个换行符:

RegExReplace(Clipboard, "(?<=[^\r\n\t ][^\r\n])\R(?=[^\r\n][^\r\n\t ])", " ")

出于某种原因,\S它似乎不适用于后瞻和前瞻。至少,不是我的测试。

于 2012-06-09T11:27:01.237 回答
1
#SingleInstance force

#v::
    Send ^c
    ClipWait
    ClipSaved = %clipboard%

    Loop
    {
        StringReplace, ClipSaved, ClipSaved, `r`n`r`n, `r`n, UseErrorLevel
        if ErrorLevel = 0  ; No more replacements needed.
            break
    }
    Clipboard := ClipSaved
    return
于 2012-09-19T07:12:51.003 回答
1
Clipboard := RegExReplace(Clipboard, "(\S+)\R", "$1 ")
于 2012-05-05T20:50:41.760 回答
1

我相信这会奏效:

text=
(
This is a test. 
This 
is a test.

This is a test. 
This is a 
test.
)
MsgBox %    RegExReplace(text,"\S\K\v(?=\S)",A_Space)
于 2012-06-04T07:00:20.173 回答