我有一个带有两个字符串变量的大数据集:people_attending
和special_attendee
:
*Example generated by -dataex-. To install: ssc install dataex
clear
input str148 people_attending str16 special_attendee
"; steve_jobs-apple_CEO; kevin_james-comedian; michael_crabtree-football_player; sharon_stone-actor; bill_gates-microsoft_CEO; kevin_nunes-politician" "michael_crabtree"
"; rob_lowe-actor; ted_cruz-politician; niki_minaj-music_artist; lindsey_whalen-basketball_coach" "niki_minaj"
end
第一个变量的长度各不相同,其中包含参加活动的每个人的列表及其标题。名称和标题用短划线隔开,与会者用分号和空格隔开。第二个变量与第一个变量中包含的名称之一完全匹配。
我想创建第三个变量,以提取第二个变量中列出的任何人的标题。在上面的示例中,我希望新变量对于观察1
为“ football_player”,对于观察2
为“ music_artist”。
这里是一种使用简单正则表达式的方法:
generate wanted = subinstr(people_attending, special_attendee, ">", .)
replace wanted = ustrregexs(0) if ustrregexm(wanted, ">(.*?);")
replace wanted = substr(wanted, 3, strpos(wanted, ";")-3)
list wanted
+-----------------+
| wanted |
|-----------------|
1. | football_player |
2. | music_artist |
+-----------------+
第一步,用标记>
代替名称。然后,使用正则表达式提取相关子字符串。在最后一步,您要清理。