正则表达式 - 查找没有中间首字母的名称

时间:2017-03-29 20:15:11

标签: mysql sql regex

我正在对SQL数据库进行查询,需要编写正则表达式来查找没有中间首字母的名称。

例如。

  • Michael J. Fox - 应该失败
  • Michael J Fox - 应该失败
  • Michael Fox - 应该通过

数据库中的全名存储在一个字符串中以供参考。

7 个答案:

答案 0 :(得分:1)

试试这个

\w{2,} \w{2,}

两个单词,空格分隔,每个至少两个字符。

答案 1 :(得分:1)

你可以做一个相当简单的事情:

^([A-Za-z]+) ([A-Za-z]+)$

答案 2 :(得分:1)

使用以下方法(对于 MySql 查询):

SELECT 
    fullname 
FROM
    table
WHERE
    fullname REGEXP '^[[:alpha:]]+[[:space:]]+[[:alpha:]]+$';

[:alpha:] - 表示与所有字母数字字符匹配的字符类

[:space:] - 表示与空格,制表符,换行符和回车符匹配的字符类

答案 3 :(得分:1)

您可以计算空格并过滤掉

之类的结果

其中长度('Michael J Fox') - 长度(替换('Michael J Fox','',''))< 2

答案 4 :(得分:0)

你不需要正则表达式。怎么样?

where name like '% %' and name not like '% % %'

这只是在名称中查找两个空格。

如果你真的只想要中间首字母,那么:

where name not like '% _ %' and name not like '% _. %'

答案 5 :(得分:0)

^运算符在行的开头查找字符,\ $运算符查看行的结尾。这个正则表达式将在一行中查找至少两个字符长的两个单词。

^ [a-zA-Z] {2,} [a-zA-Z] {2,} \ $

答案 6 :(得分:0)

drop table if exists t;
create table t (name text);
insert into t values ('Michael J Fox');
insert into t values ('Michael J. Fox');
insert into t values ('Michael Fox');
insert into t values ('  Michael     Fox  ');

允许前导空格和尾随空格,以及两者之间的多个空格,但只允许两组非空格字符:

select name, name REGEXP '^ *[^ ]+ +[^ ]+ *$'
from t;

rextester 演示http://rextester.com/CFID40649

+---------------------+----------------------------------+
|        name         | name REGEXP '^ *[^ ]+ +[^ ]+ *$' |
+---------------------+----------------------------------+
| Michael J Fox       |                                0 |
| Michael J. Fox      |                                0 |
| Michael Fox         |                                1 |
|   Michael     Fox   |                                1 |
+---------------------+----------------------------------+
相关问题