加入朱莉娅的正则表达式

时间:2013-12-09 19:17:51

标签: regex julia

x = r"abc"
y = r"def"
z = join([x,y], "|")

z # => r"r\"abc\"|r\"def\""

有没有办法join(并且通常操纵)Regex只处理正则表达式内容(即不会将r修饰符视为内容的一部分)。 z的所需输出为:

z # => r"abc|def"

1 个答案:

答案 0 :(得分:5)

macro p_str(s) s end
x = p"abc"
y = p"def"
z = Regex(join([x,y], "|"))

r“quote”运算符实际上为你编译了一个需要时间的正则表达式。如果您只想使用正则表达式的一部分来构建更大的正则表达式,那么您应该使用“常规引号”存储这些部分。

但是你用r“引用”与“常规引号”得到的粗略逃避规则呢?如果你想要粗略的r“引用”规则而不是立即编译正则表达式,那么你可以使用如下的宏:

macro p_str(s) s end

现在你有一个p“quote”,它像r“quote”一样转义但只返回一个字符串。

不要偏离主题,但你可能会定义一堆引号来绕过棘手的字母表。这是一些方便的:

                                       # "baked\nescape"    -> baked\nescape
macro p_mstr(s) s end                  # p"""raw\nescape""" -> raw\\nescape
macro dq_str(s) "\"" * s * "\"" end    # dq"with quotes"    -> "with quotes"
macro sq_str(s) "'" * s * "'" end      # sq"with quotes"    -> 'with quotes'
macro s_mstr(s) strip(lstrip(s))  end  # s"""  "stripme" """-> "stripme"

当你完成片段制作后,你可以加入并制作一个正则表达式:

myre = Regex(join([x, y], "|"))

就像你想的那样。

如果您想了解有关对象的成员(例如Regex.pattern)的更多信息,请尝试:

julia> dump(r"pat")
Regex 
  pattern: ASCIIString "pat"
  options: Uint32 33564672
  regex: Array(Uint8,(61,)) [0x45,0x52,0x43,0x50,0x3d,0x00,0x00,0x00,0x00,0x28  …   0x1d,0x70,0x1d,0x61,0x1d,0x74,0x72,0x00,0x09,0x00]