Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude strings of pattern "abba"

Tags:

regex

For example, I want to exclude 'fitting', 'hollow', 'trillion'
but not 'hello' or 'pattern'

I already got the following to work

(.)(.)\2\1

which matches 'hollow' or 'fitting', but I have trouble negating this.

the closest thing I get is

^.(?!(.)(.)\2\1)

which excludes 'fitting' and 'hollow' but not 'trillion'

like image 758
tyt2y3 Avatar asked Apr 05 '14 14:04

tyt2y3


People also ask

How do you exclude a string in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What does Str_trim () Do what's the opposite of Str_trim ()?

The function str_trim() trims the whitespace from a string. The opposite of str_trim() is str_pad() which adds characters to each side.

How do you check if a string follows a pattern?

The idea is very simple. For every pair (x, y) of consecutive characters in the pattern string, we find the last occurrence of x and first occurrence of y in the input string. If last occurrence of character x is after first occurrence of character y for any pair, we return false.

What does regexp do matlab?

Perform Case-Insensitive Matches By default, regexp performs case-sensitive matching. The regular expression specifies that the character vector: Begins with any number of alphanumeric or underscore characters, \w* . Ends with the literal text case .


2 Answers

It's a little different from what you have. Your current regex will check for the pallindromicity (?) as of the second character. Since you want to check the whole string, you need to change it a little to:

^(?!.*(.)(.)\2\1)

The first anchor will ensure that the check is made only at the beginning (otherwise, the regex can claim a match at the end of the string).

Then the .* within the negative lookahead will enable the check to be done anywhere within the string. If there's any match, fail the entire match.

like image 55
Jerry Avatar answered Sep 19 '22 14:09

Jerry


It doesn't match with trillion because you added ^. means it must have a character before the match from beginning. For your first two cases it has h and f character. So if you change this into ^..(?!(.)(.)\2\1) then it will work for trillion.

So in general the regex will be:

(?!.*(.)(.)\2\1)
   ^^ any number of characters(other than \n)
like image 42
Sabuj Hassan Avatar answered Sep 19 '22 14:09

Sabuj Hassan