【问题标题】:Need to extract String in between strings using REGEXEXTRACT() in Google Sheet需要在 Google Sheet 中使用 REGEXEXTRACT() 提取字符串之间的字符串
【发布时间】:2021-12-28 03:49:17
【问题描述】:

我有一个这样的字符串:"abcd abcd | abcde | Degree SP | xyz abcd | abcd ABC"

我需要使用正则表达式提取"Degree SP"。我怎样才能做到这一点?这里的条件是:

  • 字符串以“SP”结尾
  • 字符串在最后一个“|”之后开始。

我正在尝试使用 Google 表格公式 REGEXEXTRACT(<input string>, "[\|\s].+SR[\s\|]") 它返回" | abcde | Degree SP "。如何限制从最后一个 "|" 中提取?

【问题讨论】:

  • 感谢您的努力,Degree SP 前后是否真的有**,我已经在您的问题中进行了编辑以删除代码标签的引号,请确认或将您的示例编辑为说清楚点,谢谢。
  • 感谢@RavinderSingh13 通知我关于**,这是一个错误。我只是编辑帖子并将其删除。

标签: regex google-sheets-formula nsregularexpression


【解决方案1】:

如果字符串Degree SP应该在管道和空格之间:

\|\s([^\s|][^|]*SP)\s\|
  • \|\s 匹配 | 和一个空格字符
  • ( 捕获第一组
    • [^\s|] 匹配除空格以外的单个字符或|
    • [^|]*SP 匹配 | 以外的可选字符并匹配 SP
  • )关闭第一组
  • \s\| 匹配一个空白字符和|

Regex demo

如果只有Degree SP 之后的管道是强制性的:

([^\s|][^|]*SP)\s*\|

Regex demo

【讨论】:

  • 谢谢@第四只鸟你的解决方案真是太棒了。它解决了这个问题。这节省了我大量的时间。我有另一个与此有关的问题。字符串模式是“ | | | Word1 Word2 | | ”。此案例模式在目标区域“Word1 Word2”之前是静态的。我尝试使用“^.*?\|.*?\|.*?\|.*?([^\\|]\S+)”并得到“Word1”。但我需要“Word2”。有时如果这个字符串只有一个单词。
  • @Swopno 如果你想捕获管道之间的最后一个单词=REGEXEXTRACT(A1,"^[^|\n]*\|[^|\n]*\|[^|\n]*\|(?:\s*([^|\s]+))+") 看到这个regex demo
  • 谢谢。实际上,我也在寻找选项(勾号)。
【解决方案2】:

使用您显示的示例,请尝试以下正则表达式。

^.*?\s+\S+\s+\|\s+\S+\s+\|\s+([^\\|]*)\s+\|.*$

Online demo for above regex

您想在|SP 字符串结尾的第二次和第三次出现之间捕获值,然后尝试以下正则表达式:

^.*?\s+\S+\s+\|\s+\S+\s+\|\s+([^\\|]*SP)\s+\|.*$

Online demo for above regex

说明:为上述添加详细说明。

^.*?\s+\S+\s+  ##Matching from starting of value with a lazy match till 1st occurrence of spaces followed by 1 or more non-spaces followed by 1 or more spaces.
\|\s+\S+\s+\|  ##Matching |(literal) followed by spaces followed by 1 or more non-spaces followed by spaces with |(literal character) here.
\s+            ##Matching 1 or more spaces occurrences here.
([^\\|]*)      ##Creating 1 and only capturing group which has everything till next occurrence of | to get Degree SP value mentioned by OP in samples.
\s+\|.*$       ##Matching 1 or spaces followed by | till last of value/line.

【讨论】:

  • 感谢您的回答。但字符串模式因情况而异。 “|”的出现非常在不同的情况下。实际上,我需要一个基于字符串“SP |”定义位置的解决方案。希望这是有道理的。
  • @Swopno,好的,请您尝试一下正则表达式\b(\S+\s+SP)\s+\|,如果这对您有帮助,请告诉我?
猜你喜欢
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
相关资源
最近更新 更多