I want to extract data from string I have but I don’t know how to do it with regex.
The string is:
validate[required,maxSize[255],....]
‘….’ means it maybe another digits and letters.
So what is the regex I should use to extract the 255 value ? (the maxsize value).
Depending on the string you can be really lazy and simply match on
/maxSize\[(\d+)\]/If you want to ensure it’s inside
validate[...]it will become much, much harder unless you safely know it will occur only once and there won’t be additional[..]blocks inside:If the mentioned restrictions are not acceptable, you cannot do it with regexes – they are not powerful enough to match things such as properly nested brackets. In case you are trying to parse the full validation rule, consider using a proper parser. In that case I’d extract the
validate[...]part first by searching forvalidate[and then proceeding one char by another while counting[and]occurrences to see when the first one closes. Then I’d split the string between those brackets using,as the delimiter and then use either the parser I already have or a regex to extract the length. Since you could pretty much reuse the parser I’d go with that one; it could even give you a nicely structured objects for the whole validation rule (even ones with multiple parameters) instead of just a bunch of strings/integers.