使用Stringr查找和替换字符串

时间:2019-07-04 09:03:04

标签: r regex stringr stringi

我正在尝试查找和替换由字符串组成的数据帧的某些值。像下面这样的简单案例,

library(stringr)
test1 <- c("one", "two", "three")
str_replace_all(string = test1,
                pattern = c('one' = "1ne",
                            'three' = "3ree"))
> [1] "1ne"  "two"  "3ree"

但是,像下面这样的更复杂的情况不起作用。我在这里做错了什么?

test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
str_replace_all(string = test2,
                   pattern = c('one (1) x1' = "X1",
                               'two (2) x2' = "X2"))
> [1] "one (1) x1"   "two (2) x2"   "three (3) x3"

1 个答案:

答案 0 :(得分:1)

使用固定格式以避免正则表达式匹配

<?php

$dynamic_list = "AZ, CA, CO";
$static_list = "MN,WA,IA";
$search = "AZ";

if (strpos($dynamic_list . ',' . $static_list, $search) === false) {
    echo 'not found: String '.$search.' was not found in lists';
} else {
    echo 'found';
}