如何从PostgreSQL字符串中提取以特定字符开头的所有单词?

huangapple go评论114阅读模式
英文:

How to extract all words starting with specific character from string in PostgreSQL?

问题

我正在尝试提取所有以'M'字符开头的单词。

例如,我有一个字符串:

  1. "[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]"

我想要得到:"Mary, Max"

我尝试使用 regex_replace(\[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}\], '\\W', '', 'g') 来仅保留单词,但不知道提取所有以'M'开头的单词的正确正则表达式。我还尝试了这个:substring("name Mary type Dog name Max type Dog" from '\\w*M\\w*'),但这只给我一个单词。

英文:

I am trying to extract all words that start from 'M' character.

For example I have a string:
"[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]"
I want to get: "Mary, Max"

I tried to regex_replace([{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}], '\W', '', 'g') and left only words, but don't know the correct regex to extract all words starting with 'M'. I also tried this: substring("name Mary type Dog name Max type Dog" from '\w*M\w*') but this gives me only one word.

答案1

得分: 1

你可以使用以下模式。

  1. :\s+"(?=M)(.+?)"

第一组的输出。

  1. Mary
  2. Max
英文:

You can use the following pattern.

  1. :\s+"(?=M)(.+?)"

Output for group 1.

  1. Mary
  2. Max

答案2

得分: 1

你可以使用PostgreSQL的regexp_matches函数。文档在此

这个查询可能会有帮助。

  1. SELECT array_to_string(regexp_matches(
  2. '[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]',
  3. '"name": "M\\w+"',
  4. 'g'
  5. ), ', ') AS words;

它返回一个逗号分隔的字符串。'g'标志指定返回所有结果。

另一种获得相同结果的方法是使用LIKE操作符。

  1. SELECT string_agg(value, ', ') AS words
  2. FROM jsonb_array_elements_text(
  3. '[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]'
  4. ) AS elem
  5. WHERE value LIKE 'M%';
英文:

You can use Postgresql's regexp_matches function. Documentation here.

This query might help.

  1. SELECT array_to_string(regexp_matches(
  2. '[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]',
  3. '"name": "M\w+"',
  4. 'g'
  5. ), ', ') AS words;

It returns a comma separated string. The 'g' flag specifies that all results must be returned.

One other way to get the same result is via LIKE operator.

  1. SELECT string_agg(value, ', ') AS words
  2. FROM jsonb_array_elements_text(
  3. '[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]'
  4. ) AS elem
  5. WHERE value LIKE 'M%'

答案3

得分: 1

SELECT array_to_string(
REGEXP_MATCHES(
'[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]',
'\mM\w+\M',
'g'
),
', '
) AS result;

英文:
  1. SELECT array_to_string(
  2. REGEXP_MATCHES(
  3. '[{"name": "Mary", "type": "Dog"}, {"name": "Max", "type": "Dog"}]',
  4. '\mM\w+\M',
  5. 'g'
  6. ),
  7. ', '
  8. ) AS result;

huangapple
  • 本文由 发表于 2023年6月22日 02:50:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定