In Stata, I needed to search some string values. I couldn’t use regular expressions because the strings I’m working with happen to contain regexp control characters. The following Stata code accomplishes the task without regular expressions:
Simple case: using the following code, a string can be searched
if strpos("the full string to be searched","string") > 0 {
* this will fire
display "Yes, the search string appeared somewhere in the full string."
}
if strpos("the full string to be searched","not there") > 0 {
* this will not fire
display "Yes, the search string appeared somewhere in the full string."
}
More complicated case: using the following code, a string can be searched to see if it contains *any* of the characters in a search string.
local string_to_search = "The full string to be searched"
local search_string = "wxyz"
local search_successes = 0
local len_search_string = length("`search_string'")
forvalues i = 1(1)`len_search_string' {
local char_from_search_string = substr("`search_string'",`i',1)
if strpos("`string_to_search'","`char_from_search_string'") > 0 {
local search_successes = `search_successes' + 1
}
}
if `search_successes' > 0 {
display "Yes, one of the characters in ..."
display "`search_string'"
display "... appears somewhere in ..."
display "`string_to_search'"
}
else {
display "No, none of the characters in ..."
display "`search_string'"
display "... appear anywhere in ..."
display "`string_to_search'"
}
– Eric DeRosia