Andreas Hunter
Andreas Hunter

Reputation: 5024

Regex match string where symbol is not repeated

I have like this strings:

group items % together into% FALSE

characters % that can match any single TRUE

How I can match sentences where symbol % is not repeated?

I tried like this pattern but it's found first match sentence with symbol %

[%]{1}

Upvotes: 0

Views: 149

Answers (4)

Mike F
Mike F

Reputation: 551

I am assuming that "sentence" in your question is the same as a line in the input text. With that assumption, you can use the following:

^[^%\r\n]*(%[^%\r\n]*)?$

This, along with the multi-line and global flags, will match all lines in the input string that contain 0 or 1 '%' symbols.

^ matches the start of a line
[^%\r\n]* matches 0 or more characters that are not '%' or a new line
(...)? matches 0 or 1 instance of the contents in parentheses
% matches '%' literally
$ matches the end of a line

Upvotes: 0

anubhava
anubhava

Reputation: 786261

You may use this regex in python to return failure for lines that have more than one % in them:

^(?!([^%]*%){2}).+

RegEx Demo

(?!([^%]*%){2}) is a negative lookahead that fails the match if % is found twice after line start.

Upvotes: 3

Mark Tolonen
Mark Tolonen

Reputation: 178379

Just count them (Python):

>>> s = 'blah % blah %'
>>> s.count('%') == 1
False
>>> s = 'blah % blah'
>>> s.count('%') == 1
True

With regex:

>>> re.match('[^%]*%[^%]*$','gfdg%fdgfgfd%')
>>> re.match('[^%]*%[^%]*$','blah % blah % blah')
>>> re.match('[^%]*%[^%]*$','blah % blah blah')
<re.Match object; span=(0, 16), match='blah % blah blah'>

re.match must match from start of string, use ^ (match start of string) if using re.search, which can match in the middle of a string.

>>> re.search('^[^%]*%[^%]*$','gfdg%fdgfgfd%')
>>> re.search('^[^%]*%[^%]*$','gfdg%fdgfgfd')
<re.Match object; span=(0, 12), match='gfdg%fdgfgfd'>

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522752

You could use re.search as follows:

items = ['group items % together into%', 'characters % that can match any single']
for item in items:
    output = item
    if re.search(r'^.*%.*%.*$', item):
        output = output + ' FALSE'
    else:
        output = output + ' TRUE'
    print(output)

This prints:

group items % together into% FALSE
characters % that can match any single TRUE

Upvotes: 0

Related Questions