【问题标题】:How to extract all hashtags from string by using regexp_substr如何使用 regexp_substr 从字符串中提取所有主题标签
【发布时间】:2017-08-09 21:23:11
【问题描述】:

我需要一个从表中的推文中提取所有标签的正则表达式模式。 我喜欢的数据是

select regexp_substr('My twwet #HashTag1 and this is the #SecondHashtag    sample','#\S+')
from dual

它只带来#HashTag1 而不是#SecondHashtag

我需要像#HashTag1 #SecondHashtag 这样的输出

谢谢

【问题讨论】:

  • 你说你需要那种格式的输出,但在大多数情况下你应该在不同的行中寻找输出(就像 GurV 在他的第二种方法中展示的那样)。

标签: regex oracle regexp-substr


【解决方案1】:

您可以使用regexp_replace 删除所有与您的模式不匹配的内容。

with t (col) as (
  select 'My twwet #HashTag1 and this is the #SecondHashtag    sample, #onemorehashtag'
  from dual
)
select 
  regexp_replace(col, '(#\S+\s?)|.', '\1')
from t;

生产;

#HashTag1 #SecondHashtag #onemorehashtag

regexp_substr 将返回一个匹配项。你可以做的是使用connect by将你的字符串变成一个表格:

with t (col) as (
  select 'My twwet #HashTag1 and this is the #SecondHashtag    sample, #onemorehashtag'
  from dual
)
select 
  regexp_substr(col, '#\S+', 1, level)
from t
connect by regexp_substr(col, '#\S+', 1, level) is not null;

返回:

#HashTag1
#SecondHashtag
#onemorehashtag

编辑:

\S 匹配任何非空格字符。最好使用匹配 a-z、A-Z、0-9 和 _ 的 \w。

正如@mathguy 和this 网站所评论的那样: 主题标签以字母开头,然后允许使用字母数字字符或下划线。

所以,#[[:alpha:]]\w* 模式会更好。

with t (col) as (
  select 'My twwet #HashTag1, this is the #SecondHashtag. #onemorehashtag'
  from dual
)
select 
  regexp_substr(col, '#[[:alpha:]]\w*', 1, level)
from t
connect by regexp_substr(col, '#[[:alpha:]]\w*', 1, level) is not null;

生产:

#HashTag1
#SecondHashtag
#onemorehashtag

【讨论】:

  • 这看起来不错,而第二种解决方案可能在大多数情况下更有意义。不过,您还需要处理标点符号,以及更普遍的非字母数字字符;你可能有'My hashtag is #MyHashtag, yours is #YourHashtag, etc.'之类的东西——这里的主题标签不应该把逗号作为主题标签的一部分。
  • 我刚刚检查了 Twitter 主题标签:它们必须以字母开头,并且只能包含字母、数字和下划线。所以像'#[[:alpha:]][[:alnum:]_]* 这样的东西应该可以工作。 (不确定是否还有最小长度;这很容易适应。)
  • @mathguy - 更新了答案。感谢您的评论。
猜你喜欢
  • 2021-07-30
  • 2021-06-20
  • 2019-10-26
  • 2023-01-16
  • 2021-08-04
  • 2012-06-15
  • 2012-06-26
  • 2022-01-19
  • 2021-12-25
相关资源
最近更新 更多