正则表达式用于检查末尾带有 _0、_1 的名称

Regex for checking names with _0, _1 at the end?

本文关键字:检查 用于 正则表达式      更新时间:2023-09-26

我想写一个正则表达式来捕获所有以_0, _1,结尾的名称,例如:

dog, cart_5, rat_0

我尝试了/_'d$/.test('abc_0')但它返回"狗"的假。我想了解如何确保整个组(_digit)重复 0 次或更多次?

另外,我可以在下划线后获取数字吗?我想通过java做最后一件事

我想了解如何确保整个组 (_digit) 重复 0 次或更多次?

对于零个或多个_任何数字。

(?:_'d)*$

对于零个或多个_任何数字。

(?:_'d+)*$

对于零个或多个_加 0 或 1。

(?:_[01])*$

例:

> /(?:_'d)*$/.test('abc_0')
true
> /(?:_'d)*$/.test('dog')
true

如果要查找所有以数字结尾的单词,可以使用'w+_'d+。如果只想将匹配限制为 0 或 1,请尝试 'w+_0|1

这是java中的示例代码

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Solution {
    public static void main(String[] args) {
        //Pattern p = Pattern.compile("''w+_''d+"); //uncomment the code for first case
        Pattern p = Pattern.compile("''w+_0|1");
        Matcher matcher = p.matcher("dog, cart_5a, rat_0b");
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}

输出

rat_0