gpt4 book ai didi

regex - 消除句点前的空格,除非后跟一个数字

转载 作者:行者123 更新时间:2023-12-04 22:31:03 25 4
gpt4 key购买 nike

除非句点后跟一个数字,否则如何使用 R 的正则表达式来消除句点之前的空格?

这是我所拥有的和我尝试过的:

x <- c("I have .32 dollars AKA 32 cents . ", 
"I have .32 dollars AKA 32 cents . Hello World .")

gsub("(\\s+)(?=\\.+)", "", x, perl=TRUE)
gsub("(\\s+)(?=\\.+)(?<=[^\\d])", "", x, perl=TRUE)

这给出(.32 之前没有空格):
## [1] "I have.32 dollars AKA 32 cents. "             
## [2] "I have.32 dollars AKA 32 cents. Hello World."

我想得到:
## [1] "I have .32 dollars AKA 32 cents. "             
## [2] "I have .32 dollars AKA 32 cents. Hello World."

我在这里背负着 gsub,但欢迎其他解决方案使这个问题对 future 的搜索者更有用。

最佳答案

您不需要复杂的表达式,您可以在此处使用 Positive Lookahead

> gsub(' +(?=\\.(?:\\D|$))', '', x, perl=T)
## [1] "I have .32 dollars AKA 32 cents. "
## [2] "I have .32 dollars AKA 32 cents. Hello World."

说明 :
 +        # ' ' (1 or more times)
(?= # look ahead to see if there is:
\. # '.'
(?: # group, but do not capture:
\D # non-digits (all but 0-9)
| # OR
$ # before an optional \n, and the end of the string
) # end of grouping
) # end of look-ahead

注意: 如果这些空格字符可以是任何类型的空格,只需将 ' '+ 替换为 \s+
如果您对使用 (*SKIP)(*F) 回溯动词感到满意,这里是正确的表示:
> gsub(' \\.\\d(*SKIP)(*F)| +(?=\\.)', '', x, perl=T)
## [1] "I have .32 dollars AKA 32 cents. "
## [2] "I have .32 dollars AKA 32 cents. Hello World."

关于regex - 消除句点前的空格,除非后跟一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com