简体   繁体   English

python正则表达式中的可选字符

[英]Optional Char in python regex

I have a string as below:-我有一个字符串如下:-

<option id="ps_account_type_opt_1" value="1" selected="">[ Active Directory ]</option>\n<option id="ps_account_type_opt_2" value="2">Local</option>

I was trying to get "value" from the above string using a generic regular expression similar to below one.我试图使用类似于下面的通用正则表达式从上面的字符串中获取“值”。

VARIABLE = [ Active Directory ]变量 = [活动目录]

or或者

VARIABLE = Local变量 = 本地

or或者

VARIABLE = Active Directory变量 = 活动目录

<option(.*)value="(\d+)"(.*)>VARIABLE</option>

The problem is i need to change my VARIABLE from [ Active Directory ] to \\[ Active Directory \\].问题是我需要将我的变量从 [ Active Directory ] 更改为 \\[ Active Directory \\]。 What should i change in regular expression so that "[" and "]" becomes optional.我应该在正则表达式中更改什么,以便“[”和“]”变为可选。

Try this...尝试这个...

<option[^>]+>\[?(?<VARIABLE>.+?)\]?<\/option>

Tested here: https://regex101.com/r/SonFgU/3在这里测试: https : //regex101.com/r/SonFgU/3

Put a ?放一个? after each character or group that you require to be optional.在您需要可选的每个字符或组之后。

Example: abc?示例: abc? will match both abc and ab , because the c?将匹配abcab ,因为c? is optional.是可选的。

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

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