简体   繁体   English

正则表达式提取特定部分

[英]Regular expression extract specific part

I have a string '(test)skip(test774)2;3(xx2324)' . 我有一个字符串'(test)skip(test774)2;3(xx2324)' The presence of the word 'skip' is necessary. 单词'skip'的存在是必要的。

re.search('skip[(].+[)]', args[0]).group(0)

gives me 'skip(test774)' , but not 'test774' . 给我'skip(test774)' ,但不给我'skip(test774)' 'test774' I can could use slicing [5:-1] to get 'test774' , but it's too clumsy 我可以使用切片[5:-1]来获取'test774' ,但是它太笨拙了

What the easiest way to get only the value in brackets ('test774') using regular expressions? 使用正则表达式仅获取方括号('test774')中的值的最简单方法是什么?

To isolate the text you want, use a capturing group around the part of the regex that matches that text. 要隔离所需的文本,请在与该文本匹配的正则表达式部分周围使用捕获组。

re.search('skip[(]([^)]+)[)]', args[0]).group(1)

The change I made is where you have .+ (any non-empty sequence of characters), I have ([^)]+) (a capturing group containing a non-empty sequence of characters other than ) ; 我所做的更改是在您具有.+ (任何非空字符序列),我具有([^)]+) (一个捕获组,其中包含一个非空字符序列,而不是) this means this part of the match stops just before the first ) , rather than just before the last ) , as .+ would). 这意味着比赛的这一部分在第一个)之前停止,而不是在最后一个)之前停止,如.+一样。

regex101.com demo and explanation regex101.com演示和说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM