[R] reg expr that retains only bracketed text from strings

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Jun 12 10:11:50 CEST 2019


On Wed, 12 Jun 2019 15:45:04 +1000
nevil amos <nevil.amos using gmail.com> wrote:

> # my desired desired output:
> #    [1]  ""  "(B)" "(C)"

(function(s) regmatches(
	s,
	gregexpr('\\([^)]+\\)', s)
))(c("ABC","A(B)C","AB(C)"))
# [[1]]
# character(0)
# 
# [[2]]
# [1] "(B)"
# 
# [[3]]
# [1] "(C)"

This matches all substrings that start with an ( and are followed by
non-zero amount of non-) characters, then terminated by ). If there are
multiple such substrings, all are returned.

-- 
Best regards,
Ivan



More information about the R-help mailing list