Regular expressions, an example

[This article was first published on The Data Monkey, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Why regular expressions are your friend. This is written in Stata but applies to any language where regular expressions exist.


Original version
if length(“`qx'”)==3 { /*ex: 5q0*/
local a = substr(“`qx'”, 1, 1)
local b = substr(“`qx'”, 3, 1)
}
else if substr(“`qx'”, 2, 1) == “q” & length(“`qx'”)==4 { /*ex: 5q20*/
local a = substr(“`qx'”, 1, 1)
local b = substr(“`qx'”, 3, 2)
}
else if substr(“`qx'”, 3, 1) == “q” & length(“`qx'”)==4 { /*ex: 10q5*/
local a = substr(“`qx'”, 1, 2)
local b = substr(“`qx'”, 4, 1)
}
else if length(“`qx'”)==5 { /*ex: 10q20*/
local a = substr(“`qx'”, 1, 2)
local b = substr(“`qx'”, 4, 2)
}


Regular expression version
foreach q in `qx’ {
local a = regexr(“`q'”,”q.+”,””)
local b = regexr(“`q'”,”.+q”,””)
}

To leave a comment for the author, please follow the link and comment on their blog: The Data Monkey.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)