Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

RegEx Pattern Matching

From NoSQLZoo
Revision as of 16:44, 15 July 2015 by 40166222 (talk | contribs) (Created page with "<pre class=setup> #ENCODING import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16') #MONGO from pymongo import MongoClient client = MongoClien...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
#ENCODING
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-16')
#MONGO
from pymongo import MongoClient
client = MongoClient()
client.progzoo.authenticate('scott','tiger')
db = client['progzoo']
#PRETTY
import pprint
pp = pprint.PrettyPrinter(indent=4)

Pattern Matching String

This tutorial uses RegEx to check names. We will be using find() on the collection world.

You can use '$regex':"^B" to get all the countries that start with B.

Find the countries that start with Y

pp.pprint(list(
    db.world.find({"name":{'$regex':"^F"}},{"name":1,"_id":0})
))

pp.pprint(list(db.world.find({"name":{'$regex':"^Y"}},{"name":1,"_id":0})))

You can use '$regex':"a$" to get all the countries that end with a.

Find the countries that end with Y

pp.pprint(list(
    db.world.find({"name":{'$regex':"l$"}},{"name":1,"_id":0})
))

pp.pprint(list(db.world.find({"name":{'$regex':"y$"}},{"name":1,"_id":0})))

Luxembourg has an x, so does one other country, list them both

Find the countries that contain the letter x

pp.pprint(list(
    db.world.find({"name":{'$regex':"ana"}},{"name":1,"_id":0})
))

pp.pprint(list(db.world.find({"name":{'$regex':"x"}},{"name":1,"_id":0})))