[R] pattern matching
Marc Schwartz
marc_schwartz at me.com
Mon Jan 7 22:35:45 CET 2013
On Jan 7, 2013, at 3:22 PM, Data Analytics Corp. <walt at dataanalyticscorp.com> wrote:
> Hi,
>
> I have a simple question. Suppose I have a string "x$Expensive". I want to find the position of the $ in this string; i.e., I want a function that returns 2. I tried grep, regexpr, etc with no luck, unless I'm just using them incorrectly. Any suggestions?
>
> Thanks,
>
> Walt
The problem with this specific example is that '$' is a metacharacter in regular expressions, so you have to escape it. For example:
> regexpr("\\$", "x$Expensive")
[1] 2
attr(,"match.length")
[1] 1
attr(,"useBytes")
[1] TRUE
See ?regex for more information and if appropriate, consider gregexpr():
> gregexpr("\\$", "x$Expensive$MoreText")
[[1]]
[1] 2 12
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
Regards,
Marc Schwartz
More information about the R-help
mailing list