【问题标题】:How to put character or separator before a string in R如何在R中的字符串之前放置字符或分隔符
【发布时间】:2023-04-05 02:22:01
【问题描述】:

我有一个类似的字符串:

"Father’s Name : ABC NaskarDate of Birth : 18-01-1979Permanent Address: This is the address field for the personContact Numbers : 98413***28Passport Number:PAN Number: AEFXXXXXXXLanguages Known: Tamil, English"

我想要的输出是:

"|||Father’s Name : ABC Naskar|||Date of Birth : 18-01-1979|||Permanent Address: This is the address field for the person|||Contact Numbers : 98413***28|||Passport Number:|||PAN Number: AEFXXXXXXX|||Languages Known: Tamil, English"

这意味着我想添加“|||”在某些特定字符串(例如父亲的名字)之前, 出生日期等谢谢

【问题讨论】:

    标签: r gsub strsplit


    【解决方案1】:

    我们无法找到一般模式,但根据显示的字符串,||| 分隔符似乎应该在字符串的开头 (^),只要后面有一个小写字母由大写或数字后跟大写,也在PAN 之前和XXXXLanguages 之间。在这种情况下,正则表达式环视应该可以工作。

    gsub("(?<=[a-z0-9])(?=[A-Z])|^|(?<=[XXX])(?=Lang)|(?=PAN)", "|||", str1, perl = TRUE)
    #[1] "|||Father’s Name : ABC Naskar|||Date of Birth : 18-01-1979|||Permanent Address: This is the address field for the person|||Contact Numbers : 98413***28|||Passport Number:|||PAN Number: AEFXXXXXXX|||Languages Known: Tamil, English"
    

    数据

    str1 <- "Father’s Name : ABC NaskarDate of Birth : 18-01-1979Permanent Address: This is the address field for the personContact Numbers : 98413***28Passport Number:PAN Number: AEFXXXXXXXLanguages Known: Tamil, English"
    

    【讨论】:

    • 但在语言之前,如果 PAN 编号以“B”结尾,我也会得到“B”,例如:“PAN 编号:AEF35|||B 已知语言:泰米尔语、英语“这里是 PAN 号。 AEF35B。谢谢..
    • @A.Naskar 正如我在解决方案中所说的那样,我不确定模式在这种情况下,您还需要一个模式 (?=BLang)
    【解决方案2】:
    gsub("(Father’s Name)|(Date of Birth)", "|||\\1\\2", x)
    [1] "|||Father’s Name : ABC Naskar|||Date of Birth : 18-01-1979Permanent Address: This is the address field for the personContact Numbers : 98413***28Passport Number:PAN Number: AEFXXXXXXXLanguages Known: Tamil, English"
    

    幸运的是,正则表达式 OR,"|",能够通过第二种模式进行替换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2016-03-13
      • 2015-11-06
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      相关资源
      最近更新 更多