如何检查字符串是否包含java中的任何运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19592846/
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
how to check if a string contain any of operator in java
提问by CY5
i wanted to check if string contains operand
我想检查字符串是否包含操作数
char m='if(code.matches("[,/!%<>]")) sysout("There is Operator");
';
char match[]={'(',')','=',';','{','}','[',']','+','-
','*','/','&','!','%','^','|','<','>'};
for(int i =0; i<code.length(); i++)
{
m=code.charAt(i);
for(int j=0;j<match.length;j++){
if(m==match[j]){
o++;
}
}
}
The above code can get the total no of operand use in string, but is there some easy way.
上面的代码可以获得字符串中操作数使用的总数,但是有一些简单的方法。
采纳答案by Govardhan
You can use regular expression to do the same thing with one line of code.
您可以使用正则表达式用一行代码来做同样的事情。
// (See note below about these -++--++
// || ||
// vv vv
if (stringToTest.match("[()=;{}[\]+\-*/&!%^|<>']")) {
// It has at least one of them
}
Place all the operators you need in between brackets.
将您需要的所有运算符放在括号之间。
I couldn't test above code now, but you may have to escape some operators using a back slash.
我现在无法测试上面的代码,但是您可能必须使用反斜杠来转义某些运算符。
回答by T.J. Crowder
You can use a regular expression character class to find any of a list of characters, e.g.:
您可以使用正则表达式字符类来查找任何字符列表,例如:
HashSet<Character> match = new HashSet<Character>(Arrays.asList('(',')','=',';','{','}','[',']','+','-','*','/','&','!','%','^','|','<','>');
for(int i =0; i < code.length(); i++) {
if (match.contains(code.charAt(i)) {
o++;
}
}
The [
and ]
indicate a character class. Within that, you have to escape ]
(because otherwise it looks like the end of the character class) with a backslash, and since backslashes are special in string literals, you need two. Similarly, you have to escape -
within a character class as well (unless it's the first char, but it's easier just to remember to do it). I've highlighted those with tickmarks above.
该[
和]
表示一个字符类。在其中,您必须]
使用反斜杠转义(因为否则它看起来像字符类的结尾),并且由于反斜杠在字符串文字中是特殊的,因此您需要两个。同样,您也必须-
在字符类中转义(除非它是第一个字符,但记住这样做会更容易)。我已经突出显示了上面带有刻度的那些。
Docs:
文档:
回答by Nutic
Try to use these functions
尝试使用这些功能
String.contains() - which checks if the string contains a specified sequence of char values String.indexOf() - which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
String.contains() - 检查字符串是否包含指定的字符值序列 String.indexOf() - 返回指定字符或子字符串第一次出现的字符串中的索引(此方法有 4 种变体)
instead of checking each char in array.
而不是检查数组中的每个字符。
回答by z242
If you store "match" as a hash table, your lookups will be more efficient:
如果您将“匹配”存储为哈希表,您的查找将更加高效:
##代码##