gpt4 book ai didi

正则表达式提取数字和尾随字母或空格

转载 作者:行者123 更新时间:2023-12-04 09:32:19 25 4
gpt4 key购买 nike

我目前正在尝试从始终采用相同格式的字符串中提取数据(从没有 API 支持的社交网站中抓取)

字符串示例

53.2k Followers, 11 Following, 1,396 Posts
5m Followers, 83 Following, 1.1m Posts

我目前正在使用以下正则表达式:
“[0-9]{1,5}([,.][0-9]{1,4})?”获取数字部分,保留逗号和点分隔符。

它产生的结果如下
53.2, 11, 1,396 
5, 83, 1.1

我真的需要一个正则表达式,它也会在数字部分之后抓取字符,即使它是一个空格。 IE。
53.2k, 11 , 1,396
5m, 83 , 1.1m

任何帮助是极大的赞赏

用于复制的 R 代码
  library(stringr)

string1 <- ("536.2k Followers, 83 Following, 1,396 Posts")
string2 <- ("5m Followers, 83 Following, 1.1m Posts")

info <- str_extract_all(string1,"[0-9]{1,5}([,.][0-9]{1,4})?")
info2 <- str_extract_all(string2,"[0-9]{1,5}([,.][0-9]{1,4})?")

info
info2

最佳答案

我会建议以下正则表达式模式:

[0-9]{1,3}(?:,[0-9]{3})*(?:\\.[0-9]+)?[A-Za-z]*

此模式生成您期望的输出。这是一个解释:
[0-9]{1,3}      match 1 to 3 initial digits
(?:,[0-9]{3})* followed by zero or more optional thousands groups
(?:\\.[0-9]+)? followed by an optional decimal component
[A-Za-z]* followed by an optional text unit

我倾向于尽可能使用基本的 R 解决方案,这里有一个使用 gregexprregmatches :
txt <- "53.2k Followers, 11 Following, 1,396 Posts"
m <- gregexpr("[0-9]{1,3}(?:,[0-9]{3})*(?:\\.[0-9]+)?[A-Za-z]*", txt)
regmatches(txt, m)

[[1]]
[1] "53.2k" "11" "1,396"

关于正则表达式提取数字和尾随字母或空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214612/

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