Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression (find matching characters in order)

Tags:

python

regex

Let us say that I have the following string variables:

welcome = "StackExchange 2016"
string_to_find = "Sx2016"

Here, I want to find the string string_to_find inside welcome using regular expressions. I want to see if each character in string_to_find comes in the same order as in welcome.

For instance, this expression would evaluate to True since the 'S' comes before the 'x' in both strings, the 'x' before the '2', the '2' before the 0, and so forth.

Is there a simple way to do this using regex?

like image 963
Marco Poloe Avatar asked Oct 15 '25 10:10

Marco Poloe


1 Answers

Your answer is rather trivial. The .* character combination matches 0 or more characters. For your purpose, you would put it between all characters in there. As in S.*x.*2.*0.*1.*6. If this pattern is matched, then the string obeys your condition.

For a general string you would insert the .* pattern between characters, also taking care of escaping special characters like literal dots, stars etc. that may otherwise be interpreted by regex.

like image 137
Paul Stelian Avatar answered Oct 18 '25 00:10

Paul Stelian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!