【问题标题】:Remove 1 character from both sides of a recurring substring where one digit changes in each occurrenceRemove 1 character from both sides of a recurring substring where one digit changes in each occurrence
【发布时间】:2022-12-02 06:22:50
【问题描述】:

I need to remove apostrophes from both sides of a sub-string. The substring occurs numerous times within a starting string, and one digit changes within the substring for each occurrence.

starting_string = "{'color':'Highcharts.getOptions().colors[0]','color':'Highcharts.getOptions().colors[1]','color':'Highcharts.getOptions().colors[2]'}"

substring = Highcharts.getOptions().colors[i]

desired_string = "{'color':Highcharts.getOptions().colors[0],'color':Highcharts.getOptions().colors[1],'color':Highcharts.getOptions().colors[2]}"

Above, in 'substring', 'i' represents the digit that changes in each occurrence of the substring.

The number of times 'substring' occurs in 'starting_string' will vary. This example is simplified.

【问题讨论】:

    标签: r stringr


    【解决方案1】:
    gsub("'(Highcharts\.getOptions\(\)\.colors\[[0-9]+\])'",
         "\1", starting_string)
    # [1] "{'color':Highcharts.getOptions().colors[0],'color':Highcharts.getOptions().colors[1],'color':Highcharts.getOptions().colors[2]}"
    

    Explanation of the regex:

    • the parens (Hig...) define a group that we'll reference later using \1;
    • the enveloping ' are the literal single quotes; note that these areoutsidethe paren-group, as we will want to drop them once we find them;
    • many characters have special meaning in regex, so they are backslash-escaped; here, they are (, ), [, ], and .
    • I took the liberty of inferring that i means "any number", so I replaced it with [0-9]+ which means "one or more digit"

    【讨论】:

    • And I should be slapping my hands away, and per instructions won't say tha..s, but explanations always help with regex.
    猜你喜欢
    • 2022-12-28
    • 2022-12-02
    • 2022-12-02
    • 1970-01-01
    • 2022-12-01
    • 2022-12-01
    • 2022-12-01
    • 2022-12-02
    • 2010-09-23
    相关资源
    最近更新 更多