python - 在 Python 中,如何检查字符串是否只包含某些字符?

标签 python regex search character

在Python中,如何判断一个字符串是否只包含某些字符?

我需要检查仅包含 a..z、0..9 和 . (句号),没有其他字符。

我可以遍历每个字符并检查字符是 a..z 或 0..9,还是 .但这会很慢。

我现在不清楚如何使用正则表达式。

这是正确的吗?你能建议一个更简单的正则表达式或更有效的方法吗?

#Valid chars . a-z 0-9 
def check(test_str):
    import re
    #http://docs.python.org/library/re.html
    #re.search returns None if no position in the string matches the pattern
    #pattern to search for any character other then . a-z 0-9
    pattern = r'[^\.a-z0-9]'
    if re.search(pattern, test_str):
        #Character other then . a-z 0-9 was found
        print 'Invalid : %r' % (test_str,)
    else:
        #No character other then . a-z 0-9 was found
        print 'Valid   : %r' % (test_str,)

check(test_str='abcde.1')
check(test_str='abcde.1#')
check(test_str='ABCDE.12')
check(test_str='_-/>"!@#12345abcde<')

'''
Output:
>>> 
Valid   : "abcde.1"
Invalid : "abcde.1#"
Invalid : "ABCDE.12"
Invalid : "_-/>"!@#12345abcde<"
'''

最佳答案

这是一个简单的纯 Python 实现。它应该在性能不重要时使用(包括给 future 的 Google 员工)。

import string
allowed = set(string.ascii_lowercase + string.digits + '.')

def check(test_str):
    set(test_str) <= allowed

就性能而言,迭代可能是最快的方法。正则表达式必须遍历状态机,并且集合相等解决方案必须构建一个临时集合。但是,差异不太可能很重要。如果这个功能的性能很重要,写成C扩展模块,加上switch语句(会被编译成跳转表)。

这是一个 C 实现,由于空间限制,它使用 if 语句。如果您绝对需要一点点额外的速度,请写出开关盒。在我的测试中,它的表现非常好(在针对正则表达式的基准测试中为 2 秒对 9 秒)。

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *check(PyObject *self, PyObject *args)
{
        const char *s;
        Py_ssize_t count, ii;
        char c;
        if (0 == PyArg_ParseTuple (args, "s#", &s, &count)) {
                return NULL;
        }
        for (ii = 0; ii < count; ii++) {
                c = s[ii];
                if ((c < '0' && c != '.') || c > 'z') {
                        Py_RETURN_FALSE;
                }
                if (c > '9' && c < 'a') {
                        Py_RETURN_FALSE;
                }
        }

        Py_RETURN_TRUE;
}

PyDoc_STRVAR (DOC, "Fast stringcheck");
static PyMethodDef PROCEDURES[] = {
        {"check", (PyCFunction) (check), METH_VARARGS, NULL},
        {NULL, NULL}
};
PyMODINIT_FUNC
initstringcheck (void) {
        Py_InitModule3 ("stringcheck", PROCEDURES, DOC);
}

将它包含在你的 setup.py 中:

from distutils.core import setup, Extension
ext_modules = [
    Extension ('stringcheck', ['stringcheck.c']),
],

用作:

>>> from stringcheck import check
>>> check("abc")
True
>>> check("ABC")
False

关于python - 在 Python 中,如何检查字符串是否只包含某些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1323364/

相关文章:

python - 优化 Django 中的计数查询

javascript - js中正则表达式使用+问题

javascript - 如何获取 JavaScript 正则表达式子匹配的位置?

C# - 在文件中查找一行(正则表达式)并根据另一个正则表达式获取完整的文本 block

python - 根据其他数据帧的列映射数据帧

python 列表附加不起作用

python - 将 PangoCairo 与 PyGObject API 结合使用

javascript - 仅匹配完整数字正则表达式

c# - 从 ObservableCollection<t>.Where 获取索引和对象

google-maps - 如何创建像maps.google.com这样的搜索