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

时间:2019-03-18 03:59:40

标签: r regex

我目前正在尝试从始终采用相同格式的字符串中提取数据(从不支持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

我真的需要一个正则表达式,即使它是一个空格,它也将在数字部分之后捕获字符。即

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 

5 个答案:

答案 0 :(得分:4)

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

[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"

答案 1 :(得分:0)

我们可以在正则表达式中添加可选的character参数

stringr::str_extract_all(string1,"[0-9]{1,5}([,.][0-9]{1,4})?[A-Za-z]?")[[1]]
#[1] "536.2k" "83"     "1,396" 
stringr::str_extract_all(string2,"[0-9]{1,5}([,.][0-9]{1,4})?[A-Za-z]?")[[1]]
#[1] "5m"   "83"   "1.1m"

答案 2 :(得分:0)

已更新我之前的帖子选择了多余的逗号/空格)
这样做可以满足OP提取y_ = tf.placeholder(tf.int32, [None, 1]) y_ = tf.one_hot(y_,n) # your dtype of y_ need to be tf.int32 W = tf.Variable(tf.zeros([4096, n])) b = tf.Variable(tf.zeros([n])) 的要求(没有我以前版本中多余的逗号和空白):

  

(?:[\ d] + [。,]?(?= \ d *)[\ d] * [km]?)

以前的版本:\ b(?:[\ d。,] + [km \ s]?)

trailing letter or white space after the numeric sections
Explanation:  
- (?:          indicates non-capturing group
- [\d]+        matches 1 or more digits
- [.,]?(?=\d*) matches 0 or 1 decimal_point or comma that is immediately followed ("Positive Lookahead") by 1 or more digits
- [\d]*        matches 0 or more digits
- [km\s]?      matches 0 or 1 of characters within []

请注意,OP希望在11和83之后匹配空格。

答案 3 :(得分:0)

另一个stringr选项:

new_s<-str_remove_all(unlist(str_extract_all(string2,"\\d{1,}.*\\w")),"[A-Za-z]{2,}")
strsplit(new_s," , ")

    #[[1]]
    #[1] "5m"    "83"    "1.1m "

原始

str_remove_all(unlist(str_extract_all(string2,"\\d{1,}\\W\\w+")),"[A-Za-z]{2,}")
#[1] "83 "  "1.1m"
str_remove_all(unlist(str_extract_all(string1,"\\d{1,}\\W\\w+")),"[A-Za-z]{2,}")
#[1] "536.2k" "83 "    "1,396" 

答案 4 :(得分:0)

如果即使数字部分也是空格,也希望在数字部分之后抓起字符,则可以使用模式和可选的字符类[mk ]?,包括空格:

[0-9]{1,5}(?:[,.][0-9]{1,4})?[mk ]?

Regex demo | R demo

您可以扩大字符类中字符的范围,以匹配[a-zA-Z ]?。如果您想使用量词来匹配一个字符的1+倍或单个空格,则可以使用交替:

[0-9]{1,5}(?:[,.][0-9]{1,4})?(?:[a-zA-Z]+| )?
相关问题