Python Regular expression

  • docs.python.org – re — Regular expression operations

ค้นหาตัวอักษรระหว่าง AAA และ ZZZ

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling
print (found)
# found: 1234
import re

text = 'page-0188482009-20211001-0002.json'

try:
    found = re.search('page-\w+-(.+?)-', text).group(1)
except AttributeError:
    found = ''
print (found)
# found: 20211001

หาชื่อไฟล์ที่อยู่หลัง folder ที่กำหนด

import re

text = 'content/ptn_year=2021/ptn_month=10/ptn_day=01/content-20211001.json'

try:
    found = re.search('ptn_day=\w+/(.*)', text).group(1)
except AttributeError:
    found = ''
print (found)
# found: content-20211001.json

Case Styles: Camel, Pascal, Snake

The most popular ways to combine words into a single string

  • camelCase
  • PascalCase
  • snake_case
  • kebab-case
Case StylesText
Rawuser login count
Camel CaseuserLoginCount
Pascal CaseUserLoginCount
Snake Caseuser_login_count
Snake Case (All Caps)USER_LOGIN_COUNT
Kebab Caseuser-login-count
Case Styles

Snake case to camel case

def snake_to_camel(text):
    text = ''.join(word.title() for word in text.split('_'))
    return text

st = 'user_login_count'
print(snake_to_camel(st))
# UserLoginCount

Camel case to snake case

  • docs.python.org – re — Regular expression operations
import re

def camel_to_snake(text):
  return re.sub(r'(?<!^)(?=[A-Z])', '_', text).lower()

print(camel_to_snake('userLoginCount'))
print(camel_to_snake('HTTPResponseCodeXYZ'))
# user_login_count
# h_t_t_p_response_code_x_y_z
import re

def camel_to_snake(name):
    name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()

def to_snake_case(name):
    name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    name = re.sub('__([A-Z])', r'_\1', name)
    name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
    return name.lower()

print(camel_to_snake('UserLoginCount'))
print(camel_to_snake('camel2_camel2_case'))
print(camel_to_snake('getHTTPResponseCode'))
print(camel_to_snake('HTTPResponseCodeXYZ'))
# user_login_count
# camel2_camel2_case
# get_http_response_code
# http_response_code_xyz

กรองเอาเฉพาะตัวเลข (digit) จาก string

ใช้ regular expression

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string ipString = "(66)123-456-7890 เบอร์มือถือ ";
                string opString = null;
                Console.WriteLine(ipString);

                Regex regex = new Regex(@"[^\d]");
                opString = regex.Replace(ipString, "");
                Console.WriteLine(opString);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

จะได้

(66)123-456-7890 เบอร์มือถือ
661234567890

Regex ใน C#

  1. การแทนที่ white-space ด้วยช่องว่าง 1 ช่อง
  2. การหา url จาก HREFs
  3. การเปลี่ยน Date Formats
  4. การหา protocol และ Port Number จาก URL
  5. นำ Invalid Characters ออกจาก String
  6. ตรวจสอบ email ว่า format ถูกต้องมั๊ย
  7. extract string ด้วย regex
  8. ตรวจสอบว่ามีเฉพาะตัวเลขเท่านั้น
Continue reading