The words Under construction in black text on a yellow background with diagonal black stipes surrounding it
I'm in the process of moving my site. It's still a work in progress. Please excuse the mess and broken links.

Find and Capture RegEx Matches In Python

TODO: Pull subtitle into page object

Working on a new thing:

code_start_default_section code_end_default_section

Debugging Stuff

I'm moving stuff around right now. All this below is helping me figure out where to put stuff

        -- title

Find and Capture RegEx Matches In Python

-- p

Working on a new thing:

-- code/
-- python

import re

text = "the quick brown fox"

text = re.sub(r'(q\S+) (b\S+)', r'\2 \1', text)


print(text)

-- /code

-- results/

the brown quick fox

-- /results

-- p

This is the basic way to find and captures regular
expression matches in python.

-- code/
-- python

import re

  string = 'Test Date: 2017-04-05'
  matches = re.search(r"\d\d\d\d-(\d\d)-\d\d", string)

  if matches:
      print("Entire group: ", end="")
      print(matches.group())
      print("Subgroup by index: ", end="")
      print(matches.group(1))

-- /code

-- results/

Entire group: 2017-04-05
  Subgroup by index: 04

-- /results

-- p

This is how to do it with a compiled regular expression

-- code/
-- python

import re

  string = 'Test Date: 2017-04-05'

  pattern = re.compile('\d\d\d\d-(\d\d)-\d\d')

  matches = pattern.search(string)

  if matches:
      print("Entire match: ", end="")
      print(matches.group())
      print("Subgroup by index: ", end="")
      print(matches.group(1))

-- /code

-- results/

Entire match: 2017-04-05
  Subgroup by index: 04

-- /results

-- p

Old Notes:

-- code/
-- python

with open('/tmp/output-2.csv', 'r') as input2:
    with open('/tmp/output-3.csv', 'w') as output3:
      csv_reader = csv.reader(input2)
      csv_writer = csv.writer(output3, quoting=csv.QUOTE_ALL)
      pattern = re.compile("(\d+)/(\d+)/(\d+)")
      def replacement(m):
        return f"20{m.group(3).zfill(2)}-{m.group(1).zfill(2)}-{m.group(2).zfill(2)}"
      for row in csv_reader:
        row[7] = re.sub(pattern, replacement, row[7])
        row[8] = re.sub(pattern, replacement, row[8])
        row[12] = row[12].replace('-', '')
        row[12] = row[12].replace('%', '')
        row[15] = row[15].replace('%', '')
        csv_writer.writerow(row)

-- /code


-- categories
-- Python

-- metadata
-- date: 2017-04-05 12:27:00
-- id: 29frqztn
-- status: published
-- type: post
-- SCRUBBED_NEO: false
-- site: aws