Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match patterns "begins with A or ends with B" with Python regular expression?

Tags:

python

regex

r'(^|^A)(\S+)(B$|$)'

results to matches everything, which actually equals to ^\S$.

How to write one matches "begins with A or ends with B, may both but not neither?"

PS: I also need refer to group (\S+) in the substring module.

Example:

Match Aanything, anythingB, and refer anything group in the replace.

like image 349
BOYPT Avatar asked Dec 28 '22 06:12

BOYPT


2 Answers

(^A.*B$)|(^A.*$)|(^.*B$)
like image 162
Boris Pavlović Avatar answered Apr 30 '23 22:04

Boris Pavlović


Is this the desired behavior?

var rx = /^((?:A)?)(.*?)((?:B)?)$/;
"Aanything".match(rx)
> ["Aanything", "A", "anything", ""]
"anythingB".match(rx)
> ["anythingB", "", "anything", "B"]
"AanythingB".match(rx)
> ["AanythingB", "A", "anything", "B"]
"anything".match(rx)
> ["anything", "", "anything", ""]
"AanythingB".replace(rx, '$1nothing$3');
> "AnothingB"
"AanythingB".replace(rx, '$2');
> "anything"
like image 27
Fordi Avatar answered Apr 30 '23 23:04

Fordi