View source: R/parsers_basic.R
| match_s | R Documentation |
match_s matches a string using a function and returns a desired object
type.
match_s(s)
s |
a string-parsing function. |
This parser short-cuts the pattern satisfy(b) %using% f. With match_s
you do not have to write separate predicate and processing functions b and
f when identification and parsing can be done with a single string
parsing function s.
The function s will be given a non-empty single-element character vector
as its argument, so you don't have to test for empty input, like
character(0). These two facts also often simplify further processing with
the string functions like grep, regmatches and those from the stringr
package. The function s can return any R-object when succeeding, but to
signal failure to the parser it must return the empty list(). Note that
list() output from s will be turned into a marker object, the internal
object to mark failure, by match_s(), see failed().
A parser.
match_s(s)(x): if x==null then fail()(x) else if s(x[1]) then succeed(s(x[1]))(x[-1]) else fail()(x)
expect_integers <- function(x) {
m <- gregexpr("[[:digit:]]+", x)
matches <- regmatches(x,m)[[1]]
if (length(matches)==0) {
# this means failure to detect numbers where we expected them
return(list())
} else {
return(as.numeric(matches))
}
}
match_s(expect_integers) ("12 15 16 # some comment") # success
match_s(expect_integers) ("some text") # failure
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.