Finance
Percentage value Regex
Percentages show up everywhere in finance: interest rates, discounts, tax rates and growth figures. This pattern matches an optional minus sign, a whole number, an optional decimal part, an optional single space and then the percent sign. It is a simple way to check rate fields in forms, pick out percentage columns in CSV files, or validate values before converting them to fractions. It does not cap the value at 100, because growth and change figures often exceed that. It also does not accept a leading decimal point such as .5%, so add that alternative if your users type it.
Pattern (JavaScript)
/^-?\d+(?:\.\d+)?\s?%$/Starts at the start of the line/string, then the character "-", optionally (zero or one time), then one or more digits, then (the character ".", then one or more digits), optionally (zero or one time), then a whitespace character (space, tab, newline), optionally (zero or one time), then the character "%", then the end of the line/string.
Examples
Matches
- ✓ 45%
- ✓ 12.5 %
- ✓ -3.75%
- ✓ 250%
Does not match
- ✗ %45
- ✗ 45
- ✗ 12.%
- ✗ 45 percent
Try it
0 matches (JavaScript engine)
45%
12.5 %
-3.75%
250%
%45
45
12.%
45 percentCode in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^-?\d+(?:\.\d+)?\s?%$/g;
const text = "45%";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^-?\d+(?:\.\d+)?\s?%$')
text = '45%'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^-?\d+(?:\.\d+)?\s?%$/';
$text = '45%';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^-?\\d+(?:\\.\\d+)?\\s?%$");
String text = "45%";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^-?\d+(?:\.\d+)?\s?%$`)
text := "45%"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^-?\d+(?:\.\d+)?\s?%$");
var text = "45%";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^-?\d+(?:\.\d+)?\s?%$").unwrap();
let text = "45%";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^-?\d+(?:\.\d+)?\s?%$/
text = '45%'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Why doesn't the pattern limit values to 100?
- Many real percentages are larger than 100, such as a 250% increase in revenue. If your field is a share of a whole, add a numeric range check in code after the regex passes.
- Is a space before the % sign allowed?
- Yes, one optional space is allowed because some style guides, including French typography, put a space before the sign. Multiple spaces are rejected to catch messy input.
- How do I accept .5% without a leading zero?
- Change \d+(?:\.\d+)? to (?:\d+(?:\.\d+)?|\.\d+). That adds an alternative for numbers that start with the decimal point while keeping the rest of the pattern unchanged.
Related patterns
- Accounting negative amount in parentheses^\((?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d{2})?\)$
- American Express card number shape^3[47]\d{2}[ -]?\d{6}[ -]?\d{5}$
- Bitcoin address shape^(?:[13][a-km-zA-HJ-NP-Z1-9]{25,34}|bc1[ac-hj-np-z02-9]{11,71})$
- Common ISO 4217 currency code^(?:USD|EUR|GBP|JPY|CHF|CAD|AUD|NZD|CNY|HKD|SGD|INR|AED|SAR|SEK|NOK|DKK|ZAR|BRL|MXN)$