我有以下一组数据:
Production App "Old": Service Name: ".ProdApp - Slave1"
Production App "Old": Service Name: ".ProdApp - Slave2"
Production App "Old": Service Name: ".ProdApp - Slave3"
我想要实现的目标:通过使用 RegEx 匹配引号之间第二次出现的字符串,将此数据集转换为下面的 block ,并删除它周围的引号。
Production App "Old": Service Name: .ProdApp - Slave1
Production App "Old": Service Name: .ProdApp - Slave2
Production App "Old": Service Name: .ProdApp - Slave3
我进入这个网站,并根据 StackOverflow 上的答案测试了以下模式:
测试字符串:生产应用程序“旧”:服务名称:.ProdApp - Slave1
测试于 https://regex101.com/ 进行
下面是我在 StackOverflow 上遵循并尝试其模式的问题:
问题 1 - How to remove matching quotes when quotes surrounds word that starts with : or # (regex)
1. /\"([#:][^\"]*)\"/ # Matched < ": Service Name: " > instead of ".ProdApp - Slave1", Created Group 1 < : Service Name: >
2. /"\s*([#:].+?)\s*"/ # Matched < ": Service Name: " > instead of ".ProdApp - Slave1", Created Group 1 < : Service Name: >
问题 2 - How can I match a quote-delimited string with a regex?
1. /".*?"/ # Matched the first occurrence < "Old" >
2. /"[^"]+"/ # Matched the first occurrence < "Old" >
问题 3 - RegEx: Grabbing values between quotation marks
1. /(["'])(?:(?=(\\?))\2.)*?\1/ # Matched the first occurence < "Old" >, created two groups Group 1: < " >, Group 2: < Null >
2. /"([^"]*)"/ # Matched < "Old" > and created Group 1 < Old >
问题 4 - Regex for quoted string with escaping quotes
1. /"(?:[^"\\]|\\.)*"/ # # Matched the first occurrence < "Old" >
2. /"([^"\\]*(\\.[^"\\]*)*)"/ # # Matched < "Old" > and created Group 1 < Old >
3. /"(?:\\"|.)*?"/ # Returned < null >
4. /(["\']).*?(?<!\\)(\\\\)*\1/ # Matched < "Old" > and < " >
其中最准确的两个是“.?”和/"([^"])"/,在问题 2 和 3 中找到,但随后它仅与第一次出现匹配。 我想有没有办法使用正则表达式获得第二次出现的匹配?
到目前为止,我最喜欢的是问题 3 解决方案 2 和问题 4 解决方案 2,因为它已经创建了不带引号的字符串组 1... 唯一的问题是他们只向我返回第一次出现的情况。我需要第二次出现 “.ProdApp - Slave1”、“.ProdApp - Slave2”、“.ProdApp - Slave3”等...
我不知道如何使用正则表达式获得第二次出现。
有人可以帮我吗?谢谢。
编辑:为了了解知识,我需要将此正则表达式应用于 Grafana 中查询的输出。不可能使用任何编程语言。下面是 Grafana 上已运行的查询的图像,该查询执行替换:
图像 1。我添加了 $ABC 只是为了让您可以看到我可以用另一种模式替换字符串。
图 2。它实际上是怎样的 - 它删除了该事件,而不是替换它。
它的作用:
它改变了:
Production App "Old": Status do Serviço "\.ProdSlave*" - Service Name: ".ProdApp - Slave1"
致:
Production App "Old": Service Name: ".ProdApp - Slave1"
下一步是将第二次出现的带引号的字符串替换为:
Production App "Old": Service Name: .ProdApp - Slave1
因此,正如您所看到的,由于名称巨大,可视化很难实现,因为它不适合仪表板面板。我需要删除引号以获得更好的可视化效果,并获得空间。在我看来,这也是一次很好的学习经历,因为我可以使用相同的逻辑想到许多解决方案。
最佳答案
([^"]+"[^"]+")([^"]+)"([^"]+)"
替换为 $1$2$3
https://regex101.com/r/FZncnW/1
我确信有一种更聪明的方法来编写它,但我认为这很容易阅读和维护,我更喜欢这一点:)我们正在利用组(或使用括号捕获组)。
它匹配并捕获第三个双引号(但不包括它),继续捕获到第四个引号(但不包括它)。
生产应用程序“旧”:服务名称:“.ProdApp - Slave1”
变成:
生产应用程序“旧”:服务名称:.ProdApp - Slave1
关于regex - 使用正则表达式删除/匹配字符串之间的引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73731406/