看看String包含在数组中的元素 [英] See if String Contains An Element in an Array

查看:173
本文介绍了看看String包含在数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图去通过运营商数组,看是否运营商之一位于字符串。

I am trying to go through an array of Operators to see if one of the operators is located in the String.

例如:

String[] OPERATORS    = { "<", "<=", ... };
String line = "a <= b < c ";

我怎么会去通过一个循环,检查是否操作是字符串中去?

How would I go about going through a loop that checks to see if an operator is in the string?

另外,说我的方法发现,&LT;位于字符串&LT; =

Also, say my method found that "<" is located in the string at "<= "

不过,我寻找的实际字符串&LT; =
我怎么会去占呢?

However, I am looking for the actual string " <= ". How would I go about accounting for that?

推荐答案

我会用一个正则表达式,而不是让所有的运营商数组。此外,确保运营商的确切顺序在你的正则表达式,即&LT; = 前应&LT; 同样, == 前应 =

I would use a regex instead of having array of all the operators. Also, make sure the operators are in the exact order in your regex, i.e., <= should be before <, similarly, == should be before =:

String regex = "<=|<|>=|>|==|=|\\+|-";

String line = "a <= b < c ";

Matcher matcher = Pattern.compile(regex).matcher(line);

while (matcher.find()) {
    System.out.println(matcher.start() + " : " + matcher.group());
} 

输出

2 : <=
7 : <

的诀窍是,正则表达式匹配前&LT; &LT; = ,将已经通过&LT匹配= ,因为它来自前&LT;

The trick is that, before the regex matches <, of <=, it will already be matched by <=, as it comes before <.

这篇关于看看String包含在数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆