Reputation: 43
I am looking for a RegEx that captures a series of digits surrounded by a string pattern and pads that series of digits with leading zeros up to 4 digits. At the same time all spaces should be removed from the entire string. Some examples: "F12b" should capture "12" and return "F0012b" "AB 214/3" should capture "214" and return "AB0214/3" "G0124" should capture "0124" and return the original string unchanged
The source string should adhere to the following rules: - should start with [a-zA-Z] - after the above pattern can be any number of optional spaces - the numeric sequence can be followed by another string - the numeric sequence can be any number of digits. Only if there are less than 4 digits is the sequence to be padded with leading zeros, otherwise it remains unchanged. - I am only interested in the first occurrance within a string
I am posting this question here because I don't use RegEx often enough to figure this one out, but I know it's a perfect case for RegEx. Any help is greatly appreciated, and an explanation of the expression would certainly help me understand it.
Upvotes: 2
Views: 1724
Reputation: 93026
To match that and extract the info you want, regex is fine, you can use this:
^([a-zA-Z]+)\s*(\d+)(.*)
See it here on regexr. You see only that the space has been removed in your second example, but all needed information is captured in $1
, $2
and $3
Regular expressions are a tool to match patterns. Using that pattern within a replacement method and how the replacement string can be build is completely language dependent and has nothing to do with regex. Without knowing the language this part can not be answered.
Upvotes: 2