R语言中如何用正则表达式在字母与数字间添加空格?
Got it, let's tackle this! You want to insert spaces between letters and numbers in your string vector, and regular expression lookarounds are perfect for this job—they let you match positions between characters without consuming the characters themselves.
First, let's recap your original data:
string99 <- c("Foo /10", "Foo Bar 7 / 0", "FooBar 25 / 5", "I do 156 / ")
基础方法:针对字母与数字直接相邻的情况
If you only need to handle cases where letters and numbers are directly next to each other (like Foo123 → Foo 123 or 456Bar → 456 Bar), use this Perl-style regex with lookarounds:
# 匹配字母后紧跟数字,或数字后紧跟字母的位置,插入空格 result <- gsub("(?<=[[:alpha:]])(?=[[:digit:]])|(?<=[[:digit:]])(?=[[:alpha:]])", " ", string99, perl = TRUE) # 查看结果 result #> [1] "Foo /10" "Foo Bar 7 / 0" "FooBar 25 / 5" "I do 156 / "
扩展方法:同时处理符号与字母/数字的边界
Notice that Foo /10 didn't get a space between / and 10 in the above result—since that's a symbol adjacent to a number, not a letter directly next to a number. If you want to add spaces between symbols and letters/numbers too (to clean up cases like /10 → / 10), use this extended pattern:
# 匹配字母/数字与非字母数字/空格字符的边界,插入空格 result_extended <- gsub("(?<=[[:alnum:]])(?=[^[:alnum:][:space:]])|(?<=[^[:alnum:][:space:]])(?=[[:alnum:]])", " ", string99, perl = TRUE) # 查看扩展结果 result_extended #> [1] "Foo / 10" "Foo Bar 7 / 0" "FooBar 25 / 5" "I do 156 / "
结合你的中间步骤:替换符号为逗号后加空格
If you still want to replace non-alphanumeric characters with commas first (like your initial gsub step), chain the two operations together:
# 第一步:替换非字母数字/空格为逗号 step1 <- gsub("[^[:alnum:][:space:]]", ",", string99) # 第二步:在字母/数字与逗号之间添加空格 step2 <- gsub("(?<=[[:alnum:]])(?=[^[:alnum:][:space:]])|(?<=[^[:alnum:][:space:]])(?=[[:alnum:]])", " ", step1, perl = TRUE) step2 #> [1] "Foo , 10" "Foo Bar 7 , 0" "FooBar 25 , 5" "I do 156 , "
正则逻辑解释
Let's break down the extended pattern to make it clear:
(?<=[[:alnum:]])(?=[^[:alnum:][:space:]]): Matches the position right after a letter/number and right before a symbol (non-alphanumeric, non-space), then inserts a space.(?<=[^[:alnum:][:space:]])(?=[[:alnum:]]): Matches the position right after a symbol and right before a letter/number, then inserts a space.
内容的提问来源于stack exchange,提问作者Eric Fail

