R中的Regex
Description
grep、grepl、regexpr、gregexpr和regexec在字符向量的每个元素中搜索与参数模式匹配的参数:它们在结果的格式和详细程度上有所不同。
sub和gsub分别替换第一个匹配项和所有匹配项。
Usage
- grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, fixed = FALSE, useBytes = FALSE, invert = FALSE)
- grepl(pattern, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
- regexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
- gregexpr(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
- regexec(pattern, text, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
- sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
- gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)
Arguments
- pattern:包含正则表达式的字符串;
- x,text:寻找匹配的字符向量(或者可以被as.character强制转换为字符串的其他对象);
- ignore.case:FALSE表示区分大小写,TRUE表示不区分;
- perl:逻辑值,表示是否使用perl支持的字符表达式;
- value:如果为假,则返回包含grep确定的匹配项的(整数)索引的向量;如果为真,则返回包含匹配元素本身的向量;
- fixed:如果为真,pattern是要按原样匹配的字符串;
- useBytes:如果为真,则按字节而不是按字符进行匹配;
- invert:如果为真,则返回不匹配的元素的索引或值;
- replacement:在sub和gsub中替换匹配的模式。对于fixed = FALSE,它可以包含对模式的括号子表达式的反向引用“\1”到“\9”。仅对于perl = TRUE,它还可以包含“\U”或“\L”来将替换的其余部分转换为大写或小写,“\E”转换为结束大小写转换。
Details
3种模式:
- fixed = TRUE:精确(普通)匹配;
- perl = TRUE:Perl正则匹配;
- fixed = FALSE, perl = FALSE:使用POSIX扩展正则匹配。
sub和gsub的不同仅在于替换第一个匹配项和所有匹配项。
对于regexpr、gregexpr和regexec,pattern如果为NA将会报错,否则NA是允许的,并给出一个NA匹配。
注意:R中转义需要用两个反斜杠\\。
Value
grep(value = FALSE)返回x元素的索引向量。
grep(value = TRUE)返回一个包含选定的x元素的字符向量。
grepl返回一个逻辑向量(对于x的每个元素是否匹配)。
regexpr返回一个与文本长度相同的整数向量,给出第一个匹配项的起始位置,如果没有匹配项,则返回-1,并带有一个整数向量“match.length”,给出匹配文本的长度(或-1表示没有匹配)。
gregexpr返回一个与文本长度相同的列表,其中每个元素的形式与regexpr的返回值相同,只是给出了每个匹配的起始位置。
regexec返回一个与文本长度相同的列表,如果没有匹配,则每个元素的长度为-1,或者返回一个整数序列,其中包含匹配的起始位置和与模式的圆括号子表达式对应的所有子字符串,并带有“match”属性。
sub和gsub返回与x相同长度和相同属性的字符向量。没有被替换的字符向量x的元素将不变地返回。
Examples
普通匹配
txt <- c("arm","foot","lefroo", "bafoobar")
grep("foo", txt)
[1] 2 4
Hide
grep("foo", txt, value = TRUE)
[1] "foot" "bafoobar"
普通替换
## Double all 'a' or 'b's; "\" must be escaped, i.e., 'doubled'
gsub("([ab])", "\\1_\\1_", "abc and ABC")
[1] "a_a_b_b_c a_a_nd ABC"
regexpr匹配 位置和长度
txt <- c("The", "licenses", "for", "General")
regexpr("en", txt)
[1] -1 4 -1 2
attr(,"match.length")
[1] -1 2 -1 2
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
不同匹配方式
## trim trailing white space
str <- "Now is the time "
sub(" +$", "", str) ## spaces only
[1] "Now is the time"
Hide
## what is considered 'white space' depends on the locale.
sub("[[:space:]]+$", "", str) ## white space, POSIX-style
[1] "Now is the time"
Hide
## what PCRE considered white space changed in version 8.34: see ?regex
sub("\\s+$", "", str, perl = TRUE) ## PCRE-style white space
[1] "Now is the time"
回溯引用&perl大小写转换
## capitalizing
txt <- "a test of capitalizing"
gsub("(\\w)(\\w*)", "\\U\\1\\L\\2", txt, perl=TRUE)
[1] "A Test Of Capitalizing"
Hide
gsub("\\b(\\w)", "\\U\\1", txt, perl=TRUE)
[1] "A Test Of Capitalizing"
捕获命名
## named capture
notables <- c(" Ben Franklin and Jefferson Davis",
"\tMillard Fillmore")
# name groups 'first' and 'last'
name.rex <- "(?<first>[[:upper:]][[:lower:]]+) (?<last>[[:upper:]][[:lower:]]+)"
(parsed <- regexpr(name.rex, notables, perl = TRUE))
[1] 3 2
attr(,"match.length")
[1] 12 16
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
attr(,"capture.start")
first last
[1,] 3 7
[2,] 2 10
attr(,"capture.length")
first last
[1,] 3 8
[2,] 7 8
attr(,"capture.names")
[1] "first" "last"
Hide
parse.one <- function(res, result) {
m <- do.call(rbind, lapply(seq_along(res), function(i) {
if(result[i] == -1) return("")
st <- attr(result, "capture.start")[i, ]
substring(res[i], st, st + attr(result, "capture.length")[i, ] - 1)
}))
colnames(m) <- attr(result, "capture.names")
m
}
parse.one(notables, parsed)
first last
[1,] "Ben" "Franklin"
[2,] "Millard" "Fillmore"
URL拆分
## Decompose a URL into its components.
## Example by LT (http://www.cs.uiowa.edu/~luke/R/regexp.html).
x <- "http://stat.umn.edu:80/xyz"
m <- regexec("^(([^:]+)://)?([^:/]+)(:([0-9]+))?(/.*)", x)
m
[[1]]
[1] 1 1 1 8 20 21 23
attr(,"match.length")
[1] 26 7 4 12 3 2 4
attr(,"index.type")
[1] "chars"
attr(,"useBytes")
[1] TRUE
Hide
regmatches(x, m)
[[1]]
[1] "http://stat.umn.edu:80/xyz" "http://"
[3] "http" "stat.umn.edu"
[5] ":80" "80"
[7] "/xyz"
字符提取
在R中没有找到合适的提取字符串中某一部分的函数,所以自己编写了一个如下。
比如,提取所有大写字母开头的单词。
SUB<-function(t,REG)
{
m<-gregexpr(REG, t)
start<-m[[1]]
stop<-start+attr(m[[1]],"match.length")-1
l<-length(start)
r<-rep("1",l)
for(i in 1:l)
{
r[i]<-substr(t,start[i],stop[i])
}
return(r)
}
temp<-c("I love Study",
"I have A CAT",
"there is a Blue Pen")
lapply(temp,SUB,REG="[A-Z][A-Za-z]*")

R中的Regex的更多相关文章
- R中一切都是vector
0.可以说R语言中一切结构体的基础是vector! R中一切都是vector,vecotor的每个component必须类型一致(character,numeric,integer....)!vect ...
- 简单介绍一下R中的几种统计分布及常用模型
统计学上分布有很多,在R中基本都有描述.因能力有限,我们就挑选几个常用的.比较重要的简单介绍一下每种分布的定义,公式,以及在R中的展示. 统计分布每一种分布有四个函数:d――density(密度函数) ...
- R中的par()函数的参数
把R中par()函数的主要参数整理了一下(另外本来还整理了每个参数的帮助文档中文解释,但是太长,就分类之后,整理为图表,excel不便放上来,就放了这些表的截图)
- 关于R中的mode()和class()的区别
本文原创,转载请注明出处,本人Q1273314690(交流学习) 说明:本文曾经在15年11月在CSDN发过,但是由于CSDN不支持为知笔记的发布为博客的API功能,所以,自今天起,转移到博客园(幸好 ...
- R中的name命名系列函数总结
本文原创,转载请注明出处,本人Q1273314690 R中关于给行列赋名称的函数有 dimnames,names,rowname,colname,row.names 这五个函数,初学的时候往往分不清楚 ...
- 总结——R中查看属性的函数
本文原创,转载注明出处,本人Q1273314690 R中知道一个变量的主要内容和结构,对我们编写代码是很重要的,也可以帮我们避免很多错误. 但是,R中有好几个关于属性查看的函数,我们往往不知道什么时候 ...
- R中创建not-yet-evaluated对象
create not-yet-evaluated object在R中创建 not-yet-evaluated(就是some code we will evaluated later!!)对象;然后执行 ...
- R中,去掉dataframe中的NA行
R中使用complete.cases 和 na.omit来去掉包含NA的行 现在有个一data.frame datafile如下所示 Date sulfate nitrate ID 1 ...
- 机器学习:形如抛物线的散点图在python和R中的非线性回归拟合方法
对于样本数据的散点图形如函数y=ax2+bx+c的图像的数据, 在python中的拟合过程为: ##最小二乘法 import numpy as np import scipy as sp import ...
随机推荐
- Linux把内存挂载成硬盘提高读写速度
tmpfs是一种虚拟内存文件系统正如这个定义它最大的特点就是它的存储空间在VM里面,这里提一下VM(virtual memory),VM是由linux内核里面的vm子系统管理,现在大多数操作系统都采用 ...
- leetcode第36题:有效的数独
解题思路:按行,列,3*3方格读取元素,存入字典中.若字典中该元素的值大于1,则返回false,否则返回true. class Solution: def isValidSudoku(self, bo ...
- [LC] 252. Meeting Rooms
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si ...
- css3 transform 变形属性详解
本文主要介绍了css3 属性transform的相关内容,针对CSS3变形.CSS3转换.CSS3旋转.CSS3缩放.扭曲和矩阵做了详细的讲解.希望对你有所帮助. 这个很简单,就跟border-rad ...
- Centos防火墙开启端口
linux系统对外开放80.8080等端口,防火墙设置 我们很多时候在liunx系统上安装了web服务应用后(如tomcat.apache等),需要让其它电脑能访问到该应用,而Linux系统(cent ...
- jtemplates使用+同内容列合并
function ImportStatistics(val, pros) { top.$.jBox.tip("导入已完成,正在统计整理导入的数据...", 'loading'); ...
- C 语言高效编程与代码优化
译文链接:http://www.codeceo.com/article/c-high-performance-coding.html英文原文:Writing Efficient C and C Cod ...
- Ionic3学习笔记(十六)上传头像至图床
本文为原创文章,转载请标明出处 个人做的开源 Demo 登录注册模块采用的是 Wilddog 野狗通讯云的身份认证服务,不得不说各方面和 Google 收购的 Firebase 很像,十分简单易用.其 ...
- 2020 将至,Tester 你过得还好么?
"昏天黑地地执行用例.跟踪 bug.与开发和产品争吵.工作被压在产品发布的最后阶段,因而要背负整个团队的压力,在 retro meeting 时承受着疯狂 diss......" ...
- Selenium2自动化——初体验
一.Windows下的环境搭建 1.安装Python 访问Python官网:https://www.python.org/ 2.安装setuptools与pip setuptools是Python e ...