scala - 为RE2构建一个正则表达式来忽略重音

时间:2017-04-04 18:43:20

标签: regex scala google-bigquery re2

我正在尝试构建一个正则表达式,以便在bigquery中的表中找到一个可以包含重音符号的单词。输入可能有重音符号。我在scala中对它进行编码,因此可以使用scala或使用bigquery函数来转换输入。我想一个好的解决方案可能是这样的:

input: serie
word to find: Séries

我可以在

中转换输入
r'(?i:s[éèe]r[íìi][éèe]s)'

但我认为最好将表格的列转换为:

r'(?i:s[ée]ries)'

我不知道如何解决第二种情况,或者是否有更好的解决方法。 提前致谢

2 个答案:

答案 0 :(得分:1)

  

我正在尝试构建一个正则表达式,以便在bigquery中的表中找到一个可以包含重音符号的单词。

播放以下示例

  

所以输入可以在scala中转换或使用bigquery函数

它完成了BigQuery Standard SQL中的所有内容

#standardSQL
CREATE TEMP FUNCTION latin2accents(word STRING) AS
((
  WITH lookups AS (
    SELECT 
    'y,a,e,i,o,u,c,ç,n,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,ø,Ø,Å,Á,À,Â,Ä,È,É,Ê,Ë,Í,Î,Ï,Ì,Ò,Ó,Ô,Ö,Ú,Ù,Û,Ü,Ÿ,Ç,Æ,Œ,ñ' AS accents,
    'y,a,e,i,o,u,c,c,n,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,o,O,A,A,A,A,A,E,E,E,E,I,I,I,I,O,O,O,O,U,U,U,U,Y,C,AE,OE,n' AS latins
  ), pairs AS (
    SELECT accent, latin FROM lookups, 
      UNNEST(SPLIT(accents)) AS accent WITH OFFSET AS p1, 
      UNNEST(SPLIT(latins)) AS latin WITH OFFSET AS p2
    WHERE p1 = p2
  ), map AS (
    SELECT latin, CONCAT('[', STRING_AGG(accent, ''), ']') AS accents
    FROM pairs  
    GROUP BY latin
  )
  SELECT CONCAT('(?i:', STRING_AGG(IFNULL(accents, char), ''), ')')
  FROM UNNEST(SPLIT(word, '')) char
  LEFT JOIN map
  ON char = latin
));

WITH yourTable AS (
  SELECT 'Séries' AS word UNION ALL SELECT 'Series' UNION ALL
  SELECT 'brasília' UNION ALL SELECT 'Niño' UNION ALL SELECT 'aperçu' 
), inputs AS (
  SELECT 'series' AS input UNION ALL SELECT 'Brasilia' UNION ALL
  SELECT 'nino' UNION ALL SELECT 'apercu'
)
SELECT input, word AS found_word 
FROM yourTable CROSS JOIN inputs
WHERE REGEXP_CONTAINS(word,  latin2accents(input)) = TRUE
ORDER BY input, word

输出是(我认为你想要的)

input       found_word   
-----       ----------
Brasilia    brasília     
apercu      aperçu   
nino        Niño     
series      Series   
series      Séries   

答案 1 :(得分:1)

使用Java Collator(例如参见this answer),您可以采用一种可能更简单的方法:

scala> val c = java.text.Collator.getInstance()
c: java.text.Collator = java.text.RuleBasedCollator@289747d6
scala> c.setStrength(Collator.PRIMARY)
scala> c.equals("é","E")
res24: Boolean = true
scala> c.setStrength(Collator.SECONDARY)
scala> c.equals("é","E")
res26: Boolean = false

这要考虑到您的语言环境,因为构成“基本”(等效)字符的规则在每种语言中都会有所不同。