stribizhev's (previous but unsatisfactory) answer gave me the idea to get to a general solution:
re.sub(r '(?<=\.)(\d+?)(0+)(?=[^\d]|$)', lambda m: m.group(1) + ' ' * len(m.group(2))
You need to change the sub
as follows:
print(re.sub(r '(?<=\.)([0-9]+?)(0+)(?=\D|$)', lambda m: m.group(1) + ' ' * len(m.group(2)), my_string))
Here is another approach:
my_list = [
[12345, 12.345, 12.345, 12.345],
[12340, 12.340, 12.340, 12.340],
[12300, 12.300, 12.300, 12.300],
[12000, 12.000, 12.000, 12.000]
]
format_list = ["{:8d}", "{:8.2f}", "{:8.3f}", "{:8.4f}"]
for row in my_list:
line = ["{:<8}".format(re.sub(r '(\.\d+?)0+', r '\1', y.format(x))) for x, y in zip(row, format_list)]
print("|{}|".format("|".join(line)))
Giving the output:
| 12345 | 12.35 | 12.345 | 12.345 | | 12340 | 12.34 | 12.34 | 12.34 | | 12300 | 12.3 | 12.3 | 12.3 | | 12000 | 12.0 | 12.0 | 12.0 |
I'd suggest using string format instead of regex:
int_fmt = '{:>8d}'
general_fmt = '{:>8.5g}'
float_fmt = '{:>8.1f}'
for l in my_list:
print '|'.join([int_fmt.format(l[0])] + [(float_fmt
if int(x) == x
else general_fmt).format(x) for x in l[1: ]])
output:
12345 | 12.345 | 12.345 | 12.345 12340 | 12.34 | 12.34 | 12.34 12300 | 12.3 | 12.3 | 12.3 12000 | 12.0 | 12.0 | 12.0
Word boundary. This is a zero-width assertion that matches only at the beginning or end of a word. A word is defined as a sequence of alphanumeric characters, so the end of a word is indicated by whitespace or a non-alphanumeric character.,Matches at the end of a line, which is defined as either the end of the string, or any location followed by a newline character.,Another zero-width assertion, this is the opposite of \b, only matching when the current position is not at a word boundary.,Some of the special sequences beginning with '\' represent predefined sets of characters that are often useful, such as the set of digits, the set of letters, or the set of anything that isn’t whitespace.
. ^ $ * + ? {} []\ | ()
>>>
import re
>>>
p = re.compile('ab*') >>>
p
re.compile('ab*')
>>> p = re.compile('ab*', re.IGNORECASE)
>>>
import re
>>>
p = re.compile('[a-z]+') >>>
p
re.compile('[a-z]+')
>>> p.match("") >>>
print(p.match(""))
None
>>> m = p.match('tempo')
>>> m
<re.Match object; span=(0, 5), match='tempo'>
The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string.,You can avoid sequential character matching, and replace substrings regardless of their position in relation to one another, by nesting REGEXREPLACE( ) functions.,Replaces all instances of strings matching a regular expression with a new string.,Use REGEXREPLACE( ) any time you want to find and replace data in Analytics using simple or complex pattern matching.
Syntax
REGEXREPLACE(string, pattern, new_string)
For example, the following expression evaluates to True:
REGEXFIND("jsmith@example.net", "\bexample\b")
s/regex/replacement/modifier: Substitute matched substring(s) by the replacement.,This regex match an Integer literal (for entire string with the position anchors), both positive, negative and zero.,m/regex/modifier or /regex/modifier: Match against the regex. m is optional.,A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TestRegexNumbers {
public static void main(String[] args) {
String inputStr = "abc00123xyz456_0"; // Input String for matching
String regexStr = "[0-9]+"; // Regex to be matched
// Step 1: Compile a regex via static method Pattern.compile(), default is case-sensitive
Pattern pattern = Pattern.compile(regexStr);
// Pattern.compile(regex, Pattern.CASE_INSENSITIVE); // for case-insensitive matching
// Step 2: Allocate a matching engine from the compiled regex pattern,
// and bind to the input string
Matcher matcher = pattern.matcher(inputStr);
// Step 3: Perform matching and Process the matching results
// Try Matcher.find(), which finds the next match
while (matcher.find()) {
System.out.println("find() found substring \"" + matcher.group() +
"\" starting at index " + matcher.start() +
" and ending at index " + matcher.end());
}
// Try Matcher.matches(), which tries to match the ENTIRE input (^...$)
if (matcher.matches()) {
System.out.println("matches() found substring \"" + matcher.group() +
"\" starting at index " + matcher.start() +
" and ending at index " + matcher.end());
} else {
System.out.println("matches() found nothing");
}
// Try Matcher.lookingAt(), which tries to match from the START of the input (^...)
if (matcher.lookingAt()) {
System.out.println("lookingAt() found substring \"" + matcher.group() +
"\" starting at index " + matcher.start() +
" and ending at index " + matcher.end());
} else {
System.out.println("lookingAt() found nothing");
}
// Try Matcher.replaceFirst(), which replaces the first match
String replacementStr = "**";
String outputStr = matcher.replaceFirst(replacementStr); // first match only
System.out.println(outputStr);
// Try Matcher.replaceAll(), which replaces all matches
replacementStr = "++";
outputStr = matcher.replaceAll(replacementStr); // all matches
System.out.println(outputStr);
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#!/usr/bin/env perl use strict; use warnings; my $inStr = 'abc00123xyz456_0'; # input string my $regex = '[0-9]+'; # regex pattern string in non - interpolating string # Try match / regex / modifiers(or m / regex / modifiers) my @matches = ($inStr = ~/$regex/g); # Match $inStr with regex with global modifier # Store all matches in an array print "@matches\n"; # Output: 00123 456 0 while ($inStr = ~/$regex/g) { # The built - in array variables @ - and @ + keep the start and end positions # of the matches, where $ - [0] and $ + [0] is the full match, and # $ - [n] and $ + [n] for back references $1, $2, etc. print substr($inStr, $ - [0], $ + [0] - $ - [0]), ', '; # Output: 00123, 456, 0, } print "\n"; # Try substitute s / regex / replacement / modifiers $inStr = ~s / $regex /**/ g; # with global modifier print "$inStr\n"; # Output: abc ** xyz ** _ **
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<!DOCTYPE html>
<!-- JSRegexNumbers.html -->
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Example: Regex</title>
<script>
var inStr = "abc123xyz456_7_00";
// Use RegExp.test(inStr) to check if inStr contains the pattern
console.log(/[0-9]+/.test(inStr)); // true
// Use String.search(regex) to check if the string contains the pattern
// Returns the start position of the matched substring or -1 if there is no match
console.log(inStr.search(/[0-9]+/)); // 3
// Use String.match() or RegExp.exec() to find the matched substring,
// back references, and string index
console.log(inStr.match(/[0-9]+/)); // ["123", input:"abc123xyz456_7_00", index:3, length:"1"]
console.log(/[0-9]+/.exec(inStr)); // ["123", input:"abc123xyz456_7_00", index:3, length:"1"]
// With g (global) option
console.log(inStr.match(/[0-9]+/g)); // ["123", "456", "7", "00", length:4]
// RegExp.exec() with g flag can be issued repeatedly.
// Search resumes after the last-found position (maintained in property RegExp.lastIndex).
var pattern = /[0-9]+/g;
var result;
while (result = pattern.exec(inStr)) {
console.log(result);
console.log(pattern.lastIndex);
// ["123"], 6
// ["456"], 12
// ["7"], 14
// ["00"], 17
}
// String.replace(regex, replacement):
console.log(inStr.replace(/\d+/, "**")); // abc**xyz456_7_00
console.log(inStr.replace(/\d+/g, "**")); // abc**xyz**_**_**
</script>
</head>
<body>
<h1>Hello,</h1>
</body>
</html>
Last Updated : 28 Jul, 2022
Examples:
Input: 100.020 .003 .400
Output: 100.20 .3 .400
Input: 001.200 .001 .004
Output: 1.200 .1 .4
100.20 .3 .400 1.200 .1 .4
- \d : Matches any decimal digit
\
d Matches any decimal digit, this is equivalent
to the set class[0 - 9].
100.20 .3 .400 1.200 .1 .4
152.2 .15 .0
Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.,Adapted from Leading Zeros on Notepad++ community forum:,I need them to be exactly 9 digits and if any is not then to add a leading zero So the result that I am looking for is this, You can do that in two step process, 1) add 9 0's in front of each line. 2) Keep only the last 9 digits from each line. – Toto Jun 8, 2021 at 9:04
First, prefix all lines with zeroes so all lines contain at least 9 digits:
Search: ^ Replace: 000000000[x] Regular expression[].matches newline
Second, use this regex to cut off excess zeroes from the beginning of all lines:
Search: ^ 0 * (\d { 9 }) $ Replace: \1