ficestat
ficestat

Reputation: 333

Use regex to match 3 characters in string

I have a json payload that I need to match just the SDC in the vdcLocation.

{
    "cmdbID":"d01aacda21b7c181aaaaa16dc4bcbca",
    "serialNumber":"VBlock740-4239340361f4d-0f6d9d6ad46879",
    "vdcLocation":"Data Center-San Diego (SDC)"
}

Here's the code I have so far, what am I missing?

import json
with open('test-payload.json') as json_file:
    data = json.load(json_file)
    serialNumber = data["serialNumber"]
    dataCenter = data["vdcLocation"]
    splittedSerialNumber = serialNumber.split("-") # returns splitted list
    firstPart = splittedSerialNumber[0] # accessing the first part of the splitted list
    splittedDataCenter = dataCenter.split("-")
    lastPart = splittedDataCenter[1]
    vdcLocationOnly = if (re.match^('[SDC]')$):
        print(vdcLocationOnly)

print(serialNumber)
print(splittedSerialNumber)
print(firstPart)
print(splittedDataCenter)
print(lastPart)

Upvotes: 0

Views: 184

Answers (1)

Damon Snyder
Damon Snyder

Reputation: 1372

One solution would be something like the following:

import json
import re
with open('test-payload.json') as json_file:
    data = json.load(json_file)
    serialNumber = data["serialNumber"]
    dataCenter = data["vdcLocation"]
    splittedSerialNumber = serialNumber.split("-") # returns splitted list
    firstPart = splittedSerialNumber[0] # accessing the first part of the splitted list
    splittedDataCenter = dataCenter.split("-")
    lastPart = splittedDataCenter[1]
    if "SDC" in dataCenter:
        print("found SDC using in")

    if re.search(r'\(SDC\)$', dataCenter):
        print("found SDC using re")

print(serialNumber)
print(splittedSerialNumber)
print(firstPart)
print(splittedDataCenter)
print(lastPart)

The simplest approach would be to use "SDC" in dataCenter. But if your needs are a bit more complicated and you indeed need to use a regular expression then you probably want to use re.search (see the docs).

Upvotes: 1

Related Questions