多语言环境下的正则表达式实战:校验整数、小数

发布于:2024-05-10 ⋅ 阅读:(31) ⋅ 点赞:(0)

在软件开发中,正则表达式是验证用户输入数据格式的强大工具,特别是在处理表单验证时。本文将通过JavaScript、Java、Python、C、Rust、Go、C++六种编程语言展示如何使用正则表达式来校验输入是否为整数或小数,特别强调小数点后最多保留两位的场景。让我们一起探索如何在不同语言中实现这一功能。

JavaScript 示例

const regex = /^[0-9]+(\.[0-9]{1,2})?$/;
const isValid = regex.test(inputString);
console.log(isValid); // 输出 true 或 false

Java 示例

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("^[0-9]+(\\.[0-9]{1,2})?");
        Matcher matcher = pattern.matcher(inputString);
        System.out.println(matcher.matches()); // 输出 true 或 false
    }
}

Python 示例

import re

pattern = r'^[0-9]+(\.[0-9]{1,2})?$'
is_valid = bool(re.match(pattern, input_string))
print(is_valid) # 输出 True 或 False

C 示例

#include <stdio.h>
#include <regex.h>

int main() {
    regex_t preg;
    int reti;
    char input[] = "your_input";
    char pattern[] = "^[0-9]+(\\.[0-9]{1,2})?$";

    reti = regcomp(&preg, pattern, REG_EXTENDED);
    if (reti)
        fprintf(stderr, "Could not compile regex\n");
    else if (!regexec(&preg, input, 0, NULL, 0, 0))
        printf("Matched\n");
    else
        printf("Not matched\n");

    regfree(&preg);
    return 0;
}

Rust 示例

fn main() {
    let re = regex::Regex::new(r"^[\d]+(\.\d{1,2})?$").unwrap();
    let is_match = re.is_match("your_input");
    println!("{}", is_match); // 输出 true 或 false
}

Go 示例

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := `^[0-9]+(\.[0-9]{1,2})?`
	matched, _ := regexp.MatchString(pattern, "your_input")
	fmt.Println(matched) // 输出 true 或 false
}

C++ 示例

#include <regex>
#include <iostream>

int main() {
    std::regex pattern(R"(^[0-9]+(\.[0-9]{1,2})?)$)");
    std::string input = "your_input";
    bool match = std::regex_match(input, pattern);
    std::cout << (match ? "Matched" : "Not matched") << std::endl;
    return 0;
}

以上示例展示了在不同编程语言中,通过正则表达式^[0-9]+(\.[0-9]{1,2})?$来校验一个字符串是否符合整数或最多保留两位小数的正数格式。此正则表达式从开始(^)匹配一个或多个数字([0-9]+),随后是可选的((...))小数点(\.)后跟一或两个数字(\d{1,2}),最后是结束符($)。每个示例中,将"your_input"替换为实际需要校验的字符串。


网站公告

今日签到

点亮在社区的每一天
去签到