Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a string is equal to one of the strings (with regex)

Tags:

regex

php

How could this be done with regex?

 return ( $s=='aa' || $s=='bb' || $s=='cc' || $s=='dd' ) ? 1 : 0;

I am trying:

 $s = 'aa';
 $result = preg_match( '/(aa|bb|cc|dd)/', $s );
 echo $result; // 1 

but obviously this returns 1 if $s contains one or more of the specified strings (not when it is equal to one of them).

like image 921
sanchez Avatar asked Nov 18 '14 16:11

sanchez


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

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

Use re. match() to check if a string matches a pattern re. match(pattern, string) tests if the regex pattern matches string . Use bool() on the returned match object to return a true or false value.

How do you know if a string matches a pattern?

To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.


1 Answers

You need to use start ^ and end $ anchors to do an exact string match.

$result = preg_match( '/^(aa|bb|cc|dd)$/', $s );
like image 190
Avinash Raj Avatar answered Oct 13 '22 12:10

Avinash Raj