问题描述
我要从字符串a
中提取|Request|
和下一次出现的|
之间的所有内容:
a <- "|Request|\nSample inlet port of the HIP cartridge with |overflow| formed "
gsub(".*\\|Request\\| (.+) |.*","\\1",a)
以这种方式应用gsub不会产生预期的结果。我该怎么办呢?
解决方法
您需要使用惰性点,并且假设您要替换为捕获组,那么您的输入模式应与整个输入匹配:
a <- "|Request|\nSample inlet port of the HIP cartridge with |overflow| formed "
sub("^.*\\|Request\\|\\s*(.+?)\\s*\\|.*$","\\1",a)
[1] "Sample inlet port of the HIP cartridge with"
,
您可以使用sub
捕获|Request|
之后的所有内容,直到下一个|
出现为止。
sub(".*\\|Request\\|(.*?)\\|.*",a)
#[1] "\nSample inlet port of the HIP cartridge with "