Make sure regex does not match empty string - but with a few caveats

感情迁移 提交于 2021-02-04 21:35:24

问题


There is a problem that I need to do, but there are some caveats that make it hard.

Problem: Match on all non-empty strings over the alphabet {abc} that contain at most one a.

Examples

a
abc
bbca
bbcabb

Nonexample

aa
bbaa

Caveats: You cannot use a lookahead/lookbehind.

What I have is this:

^[bc]*a?[bc]*$

but it matches empty strings. Maybe a hint? Idk anything would help

(And if it matters, I'm using python).


回答1:


As I understand your question, the only problem is, that your current pattern matches empty strings. To prevent this you can use a word boundary \b to require at least one word character.

^\b[bc]*a?[bc]*$

See demo at regex101

Another option would be to alternate in a group. Match an a surrounded by any amount of [bc] or one or more [bc] from start to end which could look like: ^(?:[bc]*a[bc]*|[bc]+)$




回答2:


The way I understood the issue was that any character in the alphabet should match, just only one a character.

Match on all non-empty strings over the alphabet... at most one a

^[b-z]*a?[b-z]*$

If spaces can be included:

^([b-z]*\s?)*a?([b-z]*\s?)*$



回答3:


You do not even need a regex here, you might as well use .count() and a list comprehension:

data = """a,abc,bbca,bbcabb,aa,bbaa,something without the bespoken letter,ooo"""

def filter(string, char):
    return [word 
        for word in string.split(",")
        for c in [word.count(char)]
        if c in [0,1]]

print(filter(data, 'a'))

Yielding

['a', 'abc', 'bbca', 'bbcabb', 'something without the bespoken letter', 'ooo']



回答4:


You've got to positively match something excluding the empty string,
using only a, b, or c letters. But can't use assertions.

Here is what you do.

The regex ^(?:[bc]*a[bc]*|[bc]+)$

The explanation

 ^                      # BOS
 (?:                    # Cluster choice
      [bc]* a [bc]*          # only 1 [a] allowed, arbitrary [bc]'s
   |                       # or,
      [bc]+                  # no [a]'s only [bc]'s ( so must be some )
 )                      # End cluster 
 $                      # EOS


来源:https://stackoverflow.com/questions/49223588/make-sure-regex-does-not-match-empty-string-but-with-a-few-caveats

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!