I want to check if the string is in the following format
I have this regex
^\d{6,8}(-\d{4})?$
But then I am stuck. I am really new at regex. Can I get some help or some pointers?
Make the -
optional and your regex works:
^\d{6,8}(-?\d{4})?$
https://regex101.com/r/uoF1HM/1/
This also would match many number formats though. Your example strings look like dates, if that is the case I'd use something stricter ( or already written eg https://stackoverflow.com/a/14566624/3783243 might be a good place to start).
You can use this function:
function checkFunc($value){
if (preg_match('/^[0-9]{6,8}(-?)[0-9]{4}$/', $value)) {
//is valid
return $value;
} else {
//is invalid
return false;
}
}
echo checkFunc("20180529-4444"); //20180529-4444
but for the first part of string, you will have to create different check for the date format
In your regex ^\\d{6,8}(-\\d{4})?$
youy have an optional group (-\\d{4})?
with a hyphen inside the group. That means that you can only match a format like \\d{6,8}
or with a hyphen \\d{6,8}-\\d{4}
but not \\d{6,8}\\d{4}
because the hyphen should be there according to the optional group.
If you want to match your values without any capturing groups you could make only the dash optional ?
That would match
^
Assert position at the start of the line \\d{6,8}
Match 6 - 8 digits -?
Match optional dash \\d{4}
Match 4 digits $
Assert position at the end of the line
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.