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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40074123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:54:08  来源:igfitidea点击:

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

javaregex

提问by lenignes

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 (i.e + and - at the start of the string only are valid symbols). I currently have word.matches("^[+=][a-zA-Z]+"), but am not sure how to change it accordingly to fit my needs. Ex: 20e48 is invalid, 204-8 is invalid, +2048 is valid and so is -2048

我正在尝试实现我自己的 atoi 版本,因此我想检查我的字符串是否包含非数字字符并处理错误,但我还希望搜索模式排除 + 和 - 符号(即 + 和 -只有在字符串的开头是有效符号)。我目前有word.matches("^[+=][a-zA-Z]+"),但不确定如何相应地更改它以满足我的需要。例如:20e48 无效,204-8 无效,+2048 有效,-2048 也是如此

采纳答案by Darshan Mehta

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.

如果任何字符串与此模式不匹配,则它不是有效输入。

回答by rentedrainbow

Try ^ followed by character you don't want to match in a square bracket. E.g. [^k] will not match k character in given string.

尝试 ^ 后跟您不想在方括号中匹配的字符。例如 [^k] 将不匹配给定字符串中的 k 个字符。

回答by StvnBrkdll

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 个或多个数字字符的任何字符串。