【问题标题】:Extract with Specific Prefix and control no. of digits in Regex- R提取特定前缀和控制编号。 Regex-R中的数字
【发布时间】:2014-08-24 07:22:26
【问题描述】:

我需要在R中提取以下模式

 (10 digits), prefix with 3, 5, 9 (e.g. 3234567890, 5234567890, 9234567890) 
 (10 digits), prefix with 4 (e.g. 4234567890)
 (10 digits), prefix with 8 (e.g. 8234567890)  

及以下

 TAM(5 digits) – e.g. TAM12345 (numbers starting with TAM and 5 digits)
 E(7 digits) – e.g. E1234567 (numbers starting with E and only 7 digits)
 A(5 digits) – e.g. A12345 (numbers starting with A and only 5 digits)

我使用 stingr 库。

我能够提取数字(带字母)- 不知道如何给出特定的前缀并限制数字

邮件在下方

These are the notice number - with high priority
3234567890 and 5234567890 and the long pending issue 9234567890 along with the discuused numbers 4234567890,8234567890.
Special messages from TAM12345,E1234567 and A12345

需要的输出

3234567890, 5234567890, 9234567890
4234567890
8234567890
TAM12345
E1234567
A12345

【问题讨论】:

  • @Mr.Flick 我在 R.I 中使用来自 stringr 包的 str_extract_all。我正在尝试通过这个函数找到相同的方法
  • 提供样本输入的字符向量以及所需的输出会更有帮助。因为str_extract_all 接受正则表达式作为模式参数。
  • @Prasanna Nandakumar。字符和数字之间是否有空格,例如discuused numbers4234567890
  • 编辑问题,字符和数字之间有空格

标签: regex r


【解决方案1】:

您可以尝试以下使用字边界\b 的代码。单词边界用于匹配单词字符和非单词字符。

> library(stringr)
> str_extract_all(x, perl('\\b(?:[35948]\\d{9}|TAM\\d{5}|E\\d{7}|A\\d{5})\\b'))
[[1]]
[1] "3234567890" "5234567890" "9234567890" "4234567890" "8234567890"
[6] "TAM12345"   "E1234567"   "A12345"

【讨论】:

    【解决方案2】:

    使用stringr 库:

    > library(stringr)
    > str_extract_all(x, perl('\\b(?:[3-589]\\d{9}|(?:TAM|A)\\d{5}|E\\d{7})\\b'))
    [[1]]
    [1] "3234567890" "5234567890" "9234567890" "4234567890" "8234567890"
    [6] "TAM12345"   "E1234567"   "A12345"
    

    使用gsubfn 库:

    > library(gsubfn)
    > strapply(x, '\\b([3-589]\\d{9}|(?:TAM|A)\\d{5}|E\\d{7})\\b', perl=T)
    [[1]]
    [1] "3234567890" "5234567890" "9234567890" "4234567890" "8234567890"
    [6] "TAM12345"   "E1234567"   "A12345" 
    

    而 base R 也可以处理这个问题。

    > regmatches(x, gregexpr('\\b(?:[3-589]\\d{9}|(?:TAM|A)\\d{5}|E\\d{7})\\b', x, perl=T))
    [[1]]
    [1] "3234567890" "5234567890" "9234567890" "4234567890" "8234567890"
    [6] "TAM12345"   "E1234567"   "A12345" 
    

    【讨论】:

    • 请注意,如果在正则表达式中没有\bstr_extract_all("A1234545453453465645", "([34589]\\d{9}|TAM\\d{5}|E\\d{7}|A\\d{5})") 之类的内容将返回两个匹配项。不确定这是否真的是理想的行为。
    • @MrFlick 不确定 OP 需要什么,但已更新并感谢。
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    相关资源
    最近更新 更多