简体   繁体   中英

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 \\]. 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

Put a ? after each character or group that you require to be optional.

Example: abc? will match both abc and ab , because the c? is optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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