Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string matches pattern

How do I check if a string matches this pattern?

Uppercase letter, number(s), uppercase letter, number(s)...

Example, These would match:

A1B2 B10L1 C1N200J1 

These wouldn't ('^' points to problem)

a1B2 ^ A10B    ^ AB400 ^ 
like image 397
DanielTA Avatar asked Sep 26 '12 05:09

DanielTA


People also ask

How do you check if a string matches a pattern in Python?

Method : Using join regex + loop + re.match() This task can be performed using combination of above functions. In this, we create a new regex string by joining all the regex list and then match the string against it to check for match using match() with any of the element of regex list.

How do you check whether a string matches a regex in Java?

Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains ...

How do I check if a string is valid in regex?

fullmatch(). This method checks if the whole string matches the regular expression pattern or not. If it does then it returns 1, otherwise a 0.


2 Answers

import re pattern = re.compile("^([A-Z][0-9]+)+$") pattern.match(string) 
like image 111
CrazyCasta Avatar answered Oct 15 '22 05:10

CrazyCasta


One-liner: re.match(r"pattern", string) # No need to compile

import re >>> if re.match(r"hello[0-9]+", 'hello1'): ...     print('Yes') ...  Yes 

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1')) True 
like image 20
nehem Avatar answered Oct 15 '22 06:10

nehem