简体   繁体   中英

extract two words before and after a character in python regex

I am trying to extract two strings before and after a certain character[for example dot(.) ] in python regex

I tried extracting the table name after the dot, but couldn't figure out to extract the database name.

EDIT: There could be multiple dots in the query variable, but i want to extract the first occurrence.

import re
query = 'select * from xxx.yyy'
table_name = re.search('\.(.*)\s', query).group(1).split(" ",2)[0]
print table_name

output:

yyy

I expect the output to be either xxx.yyy or could be in a list is fine too, like [xxx,yyy].

Any help is appreciated. Thanks.

Using pattern '(\\w+)\\.(\\w+)'

Ex:

import re
query = 'select * from xxx.yyy'
table_name = re.search('(\w+)\.(\w+)', query)
print table_name.groups()
#or
print re.search('((\w*)\.(\w*))', query).group(0)

Output:

('xxx', 'yyy')
xxx.yyy

This can be handy in learning regular expressions and also to test them out. regex101.com

This regex should solve your issue [A-Za-z]+\\.[A-Za-z0-9]+ AZ - catch capital letters az - catch small letters 0-9 - catch numbers

Here is example

Hope you find this helpful!

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