简体   繁体   English

如何从正则表达式中的模式匹配中排除某些字符?

[英]How do I exclude certain characters from pattern matching in regex?

I'm trying to implement my own version of atoi and so I want to check if my string contains non-numeric characters and handle the error, but I also also want the search pattern to exclude the + and - symbols (ie + and - at the start of the string only are valid symbols).我正在尝试实现我自己的 atoi 版本,因此我想检查我的字符串是否包含非数字字符并处理错误,但我还希望搜索模式排除 + 和 - 符号(即 + 和 -只有在字符串的开头是有效符号)。 I currently have word.matches("^[+=][a-zA-Z]+") , but am not sure how to change it accordingly to fit my needs.我目前有word.matches("^[+=][a-zA-Z]+") ,但我不确定如何相应地更改它以满足我的需要。 Ex: 20e48 is invalid, 204-8 is invalid, +2048 is valid and so is -2048例如:20e48 无效,204-8 无效,+2048 有效,-2048 也是如此

Here you go:干得好:

public static void main(String[] args) {
    String pattern = "^[+-]?[0-9]+$";
    System.out.println("20e48".matches(pattern));
    System.out.println("204-8".matches(pattern));
    System.out.println("+2048".matches(pattern));
    System.out.println("-2048".matches(pattern));
    System.out.println("2048".matches(pattern));
}

It prints:它打印:

false
false
true
true
true

Explanation:解释:

^ => Starts
[+-] => Either plus or minus sign
? => Zero or one occurance
[0-9] => Any number
+ => One or more occurance
$ => End

If any string does not match this pattern, it is not a valid input.如果任何字符串与此模式不匹配,则它不是有效输入。

Try ^ followed by character you don't want to match in a square bracket.尝试 ^ 后跟您不想在方括号中匹配的字符。 Eg [^k] will not match k character in given string.例如 [^k] 将不匹配给定字符串中的 k 个字符。

This regex may work for you:这个正则表达式可能对你有用:

^[+-]{0,1}[0-9]*[^0-9]+[0-9]*$

It matches any string that (optionally) begins with + or -, followed by 0 or more numeric characters, followed by 1 or more non-numeric characters, followed by 0 or more numeric characters.它匹配(可选)以 + 或 - 开头、后跟 0 个或多个数字字符、1 个或多个非数字字符、0 个或多个数字字符的任何字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM