python - problems using regex expressions re.search and re.compile -


a stack overflow user has kindly shown me https://pythex.org/ allows build , test regular expressions.

i have been able write expression when comes using in python re. module confused.

what don't understand when use.compile, , when re.search -->

if search text inside of brackets example , there more one, gather supposed use .group[x] x index of item want return

example

pattern = re.compile(r'view \((\d*)\)') number = pattern.search(data).group(2); 

as understand if had following, number_connections variable, when printed

view (8) view (16) view (12) 

result

print number 16 

what don't is: when there more 1 occurance of text looking how loop on them, , how count of how many there are?

for example: number.count() return, found 3 in number: (this doesn't work because match regular expression object???)     print     

but happens when there 1 of text looking in regular expression?

example

regular expression: pattern = re.compile('[a-za-z]\s[a-za-z]/[a-za-z]/[a-za-z]') email = pattern.search(data).group(1);

result

data: "email-id":"fisrtname lastname/australia/abc"}]</p></body></html> should return: firstname lastname/australia/abc 

there may or may not more 1 of these on page - in case using result[0] not work, there may 1 instance of email address on page.

now realise syntax wrong doing gave me following, i'm looking guidance on how use regular expression once have built using https://pythex.org/:

email = pattern.search(data) print email  <_sre.sre_match object @ 0x0553b090> 

it sounds me you're @ stage python regex need read bit of documentation or full tutorial—rather trying acquire knowledge in disconnected pieces.

you have access same match whether compile regex or not.

quoting jan goyvaerts, author of regexbuddy , co-author of regular expressions cookbook:

if want use same regular expression more once, should compile regular expression object. regular expression objects more efficient, , make code more readable. create one, call re.compile(regex) or re.compile(regex, flags). flags matching options described above re.search() , re.match() functions.

the regular expression object returned re.compile() provides functions re module provides directly: search(), match(), findall(), finditer(), sub() , split(). difference use pattern stored in regex object, , not take regex first parameter. re.compile(regex).search(subject) equivalent re.search(regex, subject).

for multiple matches, can use findall or finditer (more details on same page).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -