如何提取出现特定字符/字符串的确切次数的字段?

时间:2019-06-09 19:15:20

标签: sql regex oracle

我需要提取一个字符(例如ex a)在字段值中恰好出现两次的行

例如。

db.collection.find({
    $expr: {
        $anyElementTrue: {
            $map: {
                input: { $objectToArray: "$field" },
                in: { $gt: [ "$$this.v.x", 1 ] }
            }
        }
    }
})

输出中只应包含出现两次(连续或非连续)a / A的行。

因此样本o / p应该是

X   

Khaan

Amal

Ryan13

Kamala

我尝试过

X   

Khaan

Amal

但是它只给出o / p的一行

select * from mytable where regexp_like (X,'a{2}', 'i');

3 个答案:

答案 0 :(得分:3)

或者,使用REGEXP_COUNT

SQL> with test (x) as
  2    (select 'Khaan'  from dual union all
  3     select 'Amal'   from dual union all
  4     select 'Ryan13' from dual union all
  5     select 'Kamala' from dual
  6    )
  7  select x
  8  from test
  9  where regexp_count(x, 'a', 1, 'i') = 2;

X
------
Khaan
Amal

SQL>

答案 1 :(得分:2)

模式'a{2}'的含义是char 'a'连续出现两次。
您可以通过以下语句获得所需的信息:

select * from mytable
where length(X) - length(replace(lower(X),'a', '')) = 2

不区分大小写。
它删除所有出现的a,并从初始字符串的长度中减去剩余字符串的长度。如果结果为2,则返回字符串。
请参见demo
结果:

> | X     |
> | :---- |
> | Khaan |
> | Amal  |

编辑。
对于像“ abc”这样的字符串,请使用以下命令:

select * from mytable
where length(X) - length(replace(lower(X),'abc', '')) = 2 * length('abc')

答案 2 :(得分:1)

您不需要正则表达式:

where lower(x) like '%a%a%' and
      lower(x) not like '%a%a%a%'

对于正则表达式,一种方法是:

where regexp_like(x, '^[^aA]*[aA][^aA]*[aA][^aA]*$')