如何通过重复一个字符串并插入来自数组的值来构建一个字符串

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

How to build a string by repeating a string with inserted values from an array

问题

我正在尝试构建一个正则表达式,以搜索从数组中填充的备选值。我确信有一种缩写的方法可以实现这个。

searchValues = ['aa', 'bb', 'cc']
testValue    = "|(x)"

我正在寻找一些使用testValue的神奇方式,其中它与searchValues中的项目替换x,最终得到"(aa)|(bb)|(cc)"

英文:

I'm trying to build a regular expression to search for alternative values populated from an array. I'm sure there is a shorthand way to achieve this.

searchValues = ['aa', 'bb', 'cc']
testValue    = "|(x)"

I'm looking for some magic using testValue where it is repeated with searchValues items replacing x, resulting in "(aa)|(bb)|(cc)".

答案1

得分: 2

你可以在一个推导式上使用join来转义所有的值(以防它们包含特殊字符)并形成带有交错管道的模式:

import re

searchValues = ['aa', 'bb', 'cc']
pattern = "|".join(re.escape(v) for v in searchValues)

# 'aa|bb|cc'

实际上,你不需要括号,但如果你想要它们来形成分组,你可以在推导式中添加它们:

pattern = "|".join("(" + re.escape(v) + ")" for v in searchValues)

# '(aa)|(bb)|(cc)'

如果你确定值不包含特殊字符,可以使用更短的表达式:

pattern = f"({'|'.join(searchValues)})"

如果你的值可能包含作为另一个值的前缀的字符串,你需要将较长的值放在较短的值之前。例如,使用['aab','aa','bb','cc']而不是['aa','bb','cc','aab',]。你可以通过按长度对searchValues进行排序来确保这一点:searchValues.sort(key=len,reverse=True)

英文:

You can use join on a comprehension to escape all values (in case they contain special characters) and form a pattern with interceding pipes:

import re 

searchValues = ['aa', 'bb', 'cc']
pattern = "|".join(re.escape(v) for v in searchValues)

# 'aa|bb|cc'

You don't actually need the parentheses but if you want them to form groups you can add then in the comprehension:

pattern = "|".join("("+re.escape(v)+")" for v in searchValues)

# '(aa)|(bb)|(cc)'

If you are certain that values don't contain special characters, a shorter expression can be used:

pattern = f"({')|('.join(searchValues)})"

If your values can potentially contain strings that happend to be a prefix of another value, you'll need to place the longer value before the shorter one. e.g. ['aab','aa','bb','cc'] instead of ['aa','bb','cc','aab',]. You can ensure that this is the case by sorting the searchValues on length: searchValues.sort(key=len,reverse=True)

huangapple
  • 本文由 发表于 2023年7月7日 03:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632167.html
匿名

发表评论

匿名网友

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

确定