Asked  7 Months ago    Answers:  5   Viewed   35 times

I'm trying to verify that my string matches a pattern. That is, the full string can be written as that pattern. However preg_match returns true, if any substring matches that pattern. (E.g. preg_match("#[a-z]*#, "333k") returns 1, which I don't want to. In this example I'd rather verify, the whole string contains only small Latin letters.)

 Answers

41

You use the start and end markers, ^ and $ respectively, to indicate beginning and end of the string in your regular expression pattern. That way you can make the expression match only the whole string, not any kind of substring. In your case it would then look like this:

preg_match("#^[a-z]*$#", "333k");

You can also, with one these markers, specify that the pattern must only match the beginning or the end of the string.

Wednesday, March 31, 2021
 
Whakkee
answered 7 Months ago
67

Use

preg_match('/^[a-z0-9 .-]+$/i', $firstname)
Wednesday, March 31, 2021
 
Arman
answered 7 Months ago
21

Don't use a regex when you don't need to :)

$valid = filter_var($string, FILTER_VALIDATE_IP);

Though if you really do want a regex...

$valid = preg_match('/^d{1,3}.d{1,3}.d{1,3}.d{1,3}z/', $string);

The regex however will only validate the format, the max for any octet is the max for an unsigned byte, or 255.

This is why IPv6 is necessary - an IPv4 address is only 32bits long and the internet is popular :)

Wednesday, June 23, 2021
 
saad
answered 4 Months ago
92

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here
Sunday, June 27, 2021
 
TheFrack
answered 4 Months ago
91

If you don't want to bring in a regex library for this one task...

NSString *str = @"aA09";
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""]; 
Tuesday, July 27, 2021
 
daniel__
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :