我正在尝试使用gsub替换字符串中的单词(包含在单引号中,即以单引号开头和结尾),并使用不同的单词替换存储在变量中的单词。我想保留单引号。
所以,如果我从这开始:
a <- "I am going to buy an 'apple' and a 'apple'"
repl <- "pear"
我希望它最终成为:
"I am going to buy an 'pear' and a 'pear'"
我尝试了下面这样的一些事情,但它似乎只是取代'苹果'和单引号,而我想保留单引号。
a2 <- gsub("\'apple\'", repl, a)
答案 0 :(得分:2)
您可以使用?<=
向后看?=
向前看Perl-compatible regexps
中的?gsub
语法,从gsub("(?<=\')apple(?=\')", repl, a, perl = T)
# [1] "I am going to buy an 'pear' and a 'pear'"
开始,在这种情况下,单引号就像边界一样但赢了不能替换:
(function () {
'use strict';
angular.module('i18n.setting').controller('SettingController', SettingController);
SettingController.$inject = ['$scope','SettingService'];
function SettingController($scope, SettingService) {
$scope.devicesList = [];
//$scope.scanDevices = SettingService.scanDevices($scope.devicesList);
$scope.scanDevices = SettingService.scanDevices;
//$scope.connectDevice = SettingService.connectDevice($scope.devicesList);
$scope.connectDevice = SettingService.connectDevice;
};
})();
答案 1 :(得分:1)
使用gsubfn
library(gsubfn)
gsubfn("'([^']+)'", paste0("'", repl, "'"), a)
#[1] "I am going to buy an 'pear' and a 'pear'"