【问题标题】:Extract string pattern in new variable based on other string variable基于其他字符串变量在新变量中提取字符串模式
【发布时间】:2019-12-17 06:53:13
【问题描述】:

考虑以下变量:

clear

input str18 string
"abc bcd cde"        
"def efg fgh"
"ghi hij ijk"    
end

我可以使用regexm() 函数提取所有出现的abccdedef

generate new = regexm(string, "abc|cde|def")

list

|string          new |
|--------------------|
|  abc bcd cde     1 |
|  def efg fgh     1 |
|  ghi hij ijk     0 |

我怎样才能得到以下内容?

|string            wanted  |
|--------------------------|
|  abc bcd cde     abc cde |
|  def efg fgh     def     |
|  ghi hij ijk             |

这个问题是这里回答的问题的延伸:

【问题讨论】:

  • 术语 column 在 Stata 中仅适用于矩阵或表格的列。

标签: regex stata string-matching


【解决方案1】:

我认为这是你的

  1. 有一个允许的单词列表。

  2. 希望字符串中出现在允许单词中的单词。

为此类问题寻求花哨的正则表达式解决方案是一种时尚,但您的示例至少会产生对现有单词的简单循环。但是请注意,inlist() 已宣传限制。

clear

input str18 string
"abc bcd cde"        
"def efg fgh"
"ghi hij ijk"    
end

generate wanted = "" 

generate wc = wordcount(string) 
summarize wc, meanonly 

quietly forvalues j = 1/`r(max)' { 
    replace wanted = wanted + " " + word(string, `j') if inlist(word(string, `j'), "abc", "cde", "def")
} 

replace wanted = trim(wanted) 

list 

     +----------------------------+
     |      string    wanted   wc |
     |----------------------------|
  1. | abc bcd cde   abc cde    3 |
  2. | def efg fgh       def    3 |
  3. | ghi hij ijk              3 |
     +----------------------------+

【讨论】:

    【解决方案2】:

    这是使用正则表达式的解决方案:

    clear
    
    input str18 string
    "abc bcd cde"        
    "def efg fgh"
    "ghi hij ijk"    
    end
    
    generate wanted = ustrregexra(string, "(\b((?!(abc|cde|def))\w)+\b)", " ")  
    replace wanted = strtrim(stritrim(wanted))
    
    list
    
         +-----------------------+
         |      string    wanted |
         |-----------------------|
      1. | abc bcd cde   abc cde |
      2. | def efg fgh       def |
      3. | ghi hij ijk           |
         +-----------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多