A Regular Expression that will search and replace characters from a string
-
Hello Community, I'm trying to compile a regular expression that will search for strings that exclude certain characters. For example, the following string value has 6 leading 0's 000000120 The next string excludes the 0's 121 122 I would like a regular expression that can find strings without the leading 0's and then add the 0's to it. Therefore, 121, and 122 would become 000000121 and 000000122. Can you help with this? Thanks Carlton
-
Hello Community, I'm trying to compile a regular expression that will search for strings that exclude certain characters. For example, the following string value has 6 leading 0's 000000120 The next string excludes the 0's 121 122 I would like a regular expression that can find strings without the leading 0's and then add the 0's to it. Therefore, 121, and 122 would become 000000121 and 000000122. Can you help with this? Thanks Carlton
How about:
\b[1-9]\d*\b
Demo[^] Adding the correct number of leading zeros will depend on the language you're using. For example, in C#:
string output = Regex.Replace(input, @"\b[1-9]\d*\b", match => match.Value.PadLeft(9, '0'));
In Javascript:
const output = input.replace(/\b[1-9]\d*\b/g, match => match.padStart(9, '0'));
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
How about:
\b[1-9]\d*\b
Demo[^] Adding the correct number of leading zeros will depend on the language you're using. For example, in C#:
string output = Regex.Replace(input, @"\b[1-9]\d*\b", match => match.Value.PadLeft(9, '0'));
In Javascript:
const output = input.replace(/\b[1-9]\d*\b/g, match => match.padStart(9, '0'));
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
This is fantastic. However, my platform uses javase and the following regex was able to pick out the strings without leading 0's e.g. 121 and 122. However, the regex "(9, '0')" doesn't replace 121, and 122 with 000000121 and 000000122. Nevertheless, this is great. \b[1-9]\d*\b
-
Hello Community, I'm trying to compile a regular expression that will search for strings that exclude certain characters. For example, the following string value has 6 leading 0's 000000120 The next string excludes the 0's 121 122 I would like a regular expression that can find strings without the leading 0's and then add the 0's to it. Therefore, 121, and 122 would become 000000121 and 000000122. Can you help with this? Thanks Carlton
Does it have to be regex? There's
StringUtils.leftPad ()
if you want to pad with leading 0s, as long as you know the total length you want. Or use a format string to do it.
String paddedStr = String.format("%09d", originalVal);
(I think)
We won't sit down. We won't shut up. We won't go quietly away. YouTube, and My Mu[sic], Films and Windows Programs, etc. and FB