Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检索变量Regex-Python_Python_Regex - Fatal编程技术网

检索变量Regex-Python

检索变量Regex-Python,python,regex,Python,Regex,在Python中,有没有一种方法可以检索正则表达式中的模式?例如: strA='\ta--b' 我想将“a”和“b”检索到不同的变量中您无法检索模式,您可以匹配或检索与您的模式匹配的捕获组内容 以你为例: \ta -- b 如果要检索内容,可以使用以下括号使用捕获组: \t(a) -- (b) 正则表达式对此的解释如下: \t '\t' (tab) ( group and capture to \1:

在Python中,有没有一种方法可以检索正则表达式中的模式?例如:

strA='\ta--b'


我想将“a”和“b”检索到不同的变量中

您无法检索模式,您可以匹配或检索与您的模式匹配的捕获组内容

以你为例:

\ta -- b
如果要检索内容,可以使用以下括号使用捕获组:

\t(a) -- (b)

正则表达式对此的解释如下:

\t                       '\t' (tab)
(                        group and capture to \1:
  a                        'a'
)                        end of \1
 --                      ' -- '
(                        group and capture to \2:
  b                        'b'
)                        end of \2
然后,您可以通过访问组内容的索引(如
\1
(或
$1
)和组
\2
(或
$2
)来获取组内容。但您将获取匹配的内容,而不是模式本身

因此,如果您有:

\t(\w) -- (\d)

您将获取与该模式匹配的内容:

\t                       '\t' (tab)
(                        group and capture to \1:
  \w                       word characters (a-z, A-Z, 0-9, _)
)                        end of \1
 --                      ' -- '
(                        group and capture to \2:
  \d                       digits (0-9)
)                        end of \2
但是您无法检索
\w
\d
本身

如果要获取此项的模式,请执行以下操作:

\t\w -- \d
您应该将上面的字符串按
--
拆分,您将得到以下字符串:

"\t\w "
" \d"

听起来你在说:


不使用split()方法,因为字符串的模式可能会变化
(?请描述模式如何变化(否则正则表达式可能无法匹配所有可能性)正则表达式中的模式是由什么分隔的?第一个变量是否总是跟在
\t
后面?这两个变量是否总是用“---”分隔?字符串中是否有多个模式,还是只有2个模式?是否应该
\t
\\t
>>> import re
>>> pattern = r"\t(\w+) -- (\w+)"
>>> s = '       test1 -- test2'
>>> a, b = re.search(pattern, s).groups()
>>> a
'test1'
>>> b
'test2'