0

So a document contains strings of the form:

9s5s4sKs7h6h4h2d4dAdTd2c3c
6hKhQs6s3s7s5d3d2d9dKdAd4h
5s9sTs8hKhJc4s6c4hJsAc2dKs

Every line is made up out of pairs consisting of digit/uppercase letter and a lowercase letter.

I want to look for all lines that have all pairs with the same lowercase letter grouped (next to each other) (eg. Ks or 2d). So on the first line, the pairs with 's' are all next to each other, then the 'h' pairs, then 'd' and then 'c'.

There are only 4 possible lowercase letters (s,c,d,h), so I made the following regex expression:

^.(.)(.\1)*.(.)(.\3)*.(.)(.\5)*.(.)(.\7)* .*$

but this doesn't account for a line like:

6hKhQs6s3s7s5d3d2d9dKdAd4h

where there are a few 'h' pairs at the beginning, then some other pairs and then an 'h' pair at the end. So this line shouldn't match.

I'm using the grep command for this.

Example:

grep -P "^.(.)(.\1)*.(.)(.\3)*.(.)(.\5)*.(.)(.\7)* .*$" file.txt

Input:

9s5s4sKs7h6h4h2d4dAdTd2c3c 
6hKhQs6s3s7s5d3d2d9dKdAd4h
5s9sTs8hKhJc4s6c4hJsAc2dKs

Output:

9s5s4sKs7h6h4h2d4dAdTd2c3c

On this line, we first have the pairs with 's', after that the pairs with 'h', then the pairs with 'd' and finally the pairs with 'c'.

This line 6hKhQs6s3s7s5d3d2d9dKdAd4h doesn't match because there is a group of 'h' pairs at the beginning, then some other pairs and then at the end there is an 'h' pair again. This means that they aren't grouped together and the line shouldn't match.

1
  • Please edit your question and show the complete grep command and the expected and actual output. Please add more detsils why each line in your example woukd match or not match. (I don't fully understand the current explanation.)
    – Bodo
    Jan 13, 2023 at 16:59

1 Answer 1

2

Since the letters are limited to just scdh, you could just filter out lines that have a different letter between two occurrences of a same letter with:

grep -ve 's.*[cdh].*s' -e 'c.*[sdh].*c' -e 'd.*[sch].*d' -e 'h.*[scd].*h'

Or with perl-like regexps if available:

grep -Pv '([scdh]).*(?!\1)[scdh].*\1'

Here, you'd be able to use [a-z] in place of [scdh] for any ASCII lower case letter. Or [[:lower:]] or \p{Ll} for any lower case letter in any alphabet.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .