在作为测试工程师,经常会遇到 mock 数据的时候。在 python 中也提供了相应的库根据正则表达式生成字符串的,今天就介绍几个常用库。
Exrex 推荐指数 : ⭐️⭐️
最后更新时间:2017 年 6 月 27 日
- 使用方式
import exrex
def get_random_one():
"""Returns a random string matching the regex"""
return exrex.getone('[0-9]{2}')
- 其他常用函数
exrex.generate('[0-9]{2}') #['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']
exrex.count('[0-9]{2}') #100
exrex.simplify('(ab|ac|ad)') #(a[bcd])
xeger 推荐指数 : ⭐️⭐️⭐️
最后更新时间:2019 年 8 月 2 日
- 使用方式
from xeger import Xeger
x = Xeger()
def gen_random_one():
"""Returns a random string matching the regex"""
return x.xeger('[0-9]{2}')
- 其他常用函数
无
最后更新时间:2022 年 5 月 25 日
- 使用方式
import rstr
def gen_random_one():
"""return a string between 1 and 10 characters in length"""
return rstr.rstr('ABC')
- 其他常用函数
rstr.rstr('ABC', 5, 10) #返回 5-10 位长度的字符串 'CBCCCABAA'
rstr.rstr('ABC', include='&') #返回包含 & 的字符串,'CA&A'
rstr.rstr(['A', 'B', 'C'], include = ['@'], exclude=('C',)) #返回包含 @ 不包含 C 的字符串,'BAAABBA@BAA'
- 更多支持
rstr 兼容 xeger 的用法
>>> import rstr >>> rstr.xeger(r'[A-Z]d[A-Z] d[A-Z]d') u'R6M 1W5'
附件:
| 项目名 | 最新版本 | 更新时间 | github star | pypi 链接 |
|---|---|---|---|---|
| rstr | 3.2.0 | 2022.5.25 | 51 | xstr |
| StringGenerator | 0.4.4 | 2021.5.20 | 34 | StringGenerator |
| strgen | 1.3.1 | 2020.12.6 | 2 | strgen |
| EGRET | 0.0.2 | 2019.8.16 | None | None |
| Xeger | 0.3.5 | 2019.8.2 | 98 | xeger |
| Exrex | 0.10.5 | 2017.6.25 | 714 | Exrex |



