stay with problems longer

R 정규표현식 - 1

|

R 정규표현식 - 1

R의 base 패키지에서 사용되는 정규표현식 관련 함수는

  1. grep
  2. grepl
  3. sub
  4. gsub
  5. regexpr
  6. gregexpr
  7. regexec

등이 있다.

일단, strings라는 이름의 길이가 9인 vector를 작성해보자.

strings <- c("sales1.xls", "orders3.xls", "sales2.xls", "sales3.xls", "apac1.xls", "europe2.xls", "na1.xls", "na2.xls", "sa1.xls") 
# '손에 잡히는 정규표현식 - ben forta' 참조

grep와 grepl의 결과를 살펴보자. grep는 조건에 해당하는 요소의 위치를 grepl은 T/F로 결과를 나타낸다.

grep( "r", strings)
## [1] 2 6
grepl("r", strings)
## [1] FALSE  TRUE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE

regexpr은 해당되지 않을 경우 -1로 나타내고 해당될 경우에는 해당 문자내에서의 위치를 나타낸다. gregexpr은 regexpr의 상세버전으로, 리스트로 표현된다.

regexpr( "r", strings)
## [1] -1  2 -1 -1 -1  3 -1 -1 -1
## attr(,"match.length")
## [1] -1  1 -1 -1 -1  1 -1 -1 -1
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE
gregexpr("r", strings[1:2])
## [[1]]
## [1] -1
## attr(,"match.length")
## [1] -1
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE
## 
## [[2]]
## [1] 2 5
## attr(,"match.length")
## [1] 1 1
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE

regexec는 grepexpr과 같은 형태이나 해당되는 모든 pattern을 찾아내지 않고 첫번째로 검색된 문자열만 표시한다.

regexec( "r", strings[1:2])
## [[1]]
## [1] -1
## attr(,"match.length")
## [1] -1
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE
## 
## [[2]]
## [1] 2
## attr(,"match.length")
## [1] 1
## attr(,"index.type")
## [1] "chars"
## attr(,"useBytes")
## [1] TRUE

sub의 경우 해당되는 패턴이 처음 발견되는 문자열을 대체하고 gsub의 경우에는 해당되는 모든 패턴을 대체한다.

sub( "r", "s", strings[2])
## [1] "osders3.xls"
gsub("r", "s", strings[2])
## [1] "osdess3.xls"

Comments