1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import re
- from typing import Optional, Union
- class StringUtil:
- """字符串处理工具类"""
- @staticmethod
- def is_empty(s: Optional[str]) -> bool:
- """判断字符串是否为空
-
- Args:
- s: 输入字符串
-
- Returns:
- bool: 是否为空
- """
- return s is None or len(s.strip()) == 0
- @staticmethod
- def to_camel_case(s: str) -> str:
- """将下划线命名转换为驼峰命名
-
- Args:
- s: 输入字符串
-
- Returns:
- 驼峰命名字符串
- """
- parts = s.split('_')
- return parts[0] + ''.join(x.title() for x in parts[1:])
- @staticmethod
- def to_snake_case(s: str) -> str:
- """将驼峰命名转换为下划线命名
-
- Args:
- s: 输入字符串
-
- Returns:
- 下划线命名字符串
- """
- s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s)
- return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
- @staticmethod
- def truncate(s: str, length: int, suffix: str = '...') -> str:
- """截断字符串
-
- Args:
- s: 输入字符串
- length: 最大长度
- suffix: 后缀
-
- Returns:
- 截断后的字符串
- """
- if len(s) <= length:
- return s
- return s[:length - len(suffix)] + suffix
- @staticmethod
- def is_email(s: str) -> bool:
- """验证是否为有效的邮箱地址
-
- Args:
- s: 输入字符串
-
- Returns:
- bool: 是否为有效邮箱
- """
- pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
- return bool(re.match(pattern, s))
- @staticmethod
- def is_phone(s: str) -> bool:
- """验证是否为有效的手机号码
-
- Args:
- s: 输入字符串
-
- Returns:
- bool: 是否为有效手机号
- """
- pattern = r'^1[3-9]\d{9}$'
- return bool(re.match(pattern, s))
- @staticmethod
- def join_with_comma(items: list) -> str:
- """将列表元素用逗号连接
-
- Args:
- items: 输入列表
-
- Returns:
- 连接后的字符串
- """
- return ', '.join(str(item) for item in items)
|