Click here to Skip to main content
15,790,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Like in the above ex, there are two patterns(0 -1 2 0 and 0 1 0).
What will be the syntax for finding that out using regex in python?

What I have tried:

I've tried 'r^[0\s]-\d[1-9]' but it's not working!
Updated 18-Jul-20 3:03am
BillWoodruff 18-Jul-20 19:43pm    
are you familiar enough with C# to convert an example to Python ?

1 solution

A Regex isn't about "counting" - it's a text processing system.
But ... if you locate all the "<whitespace>0<whitespace>" entires as separate groups, you could tell haw many patterns there are that match your criteria - and a Regex will tell you the number of matches.
So in your sample "1 0 -1 2 0 1 0" there are three "<whitespace>0<whitespace>" entries, so depending on how you want to process them there are two or three different "patterns": 0 -1 2 0, 0 -1 2 0 1 0, and 0 1 0

Knowing the number of zeros, tells you the patterns count.
Share this answer
BillWoodruff 18-Jul-20 19:48pm    
not sure, in this case, if the OP needs some kind of backtracking that would return 0 -1 2 0 1 0 ... given the two results the OP describes.
OriginalGriff 19-Jul-20 2:19am    
Why? If all you want is the number of simple patterns - and his sample implies that - the number of zeros tells you that - it's the number of gaps between zeros.
Or am I missing something?
BillWoodruff 19-Jul-20 3:58am    
Hi, As I see it the OP wants '0' delimited patterns, like: '0 -1 2 0'

Consider: 0 0 1 2 3

Two zeroes, one pattern: '0 0' ... unless the OP tells us more explicitly how he wants to scan, there's uncertainty about ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900