简体   繁体   English

遍历字符串。 搜索特殊字符。 使用正则表达式

[英]Iterating over string. Searching for special characters. Using regular expressions

My goal is to iterate over a string and pull out instances of certain characters.我的目标是迭代一个字符串并提取某些字符的实例。

Ideally I would want to use Pattern and Matcher.理想情况下,我想使用模式和匹配器。

For example.例如。

String str = "10+10+10"; String str = "10+10+10";

How would I go about if I wanted to make a code that would detect if the part of the string is a number or the + operator and in turn, save that part of the string in an array depending on what it is and then consequently move on to the next character?如果我想制作一个代码来检测字符串的一部分是数字还是 + 运算符,然后将字符串的那部分保存在数组中,具体取决于它的内容,然后移动,我该怎么做到下一个角色?

I am aware of that I am supposed to be using regular expressions but not exactly how I am supposed to iterate over a string and look for regular expressions from left to right.我知道我应该使用正则表达式,但不完全是我应该如何遍历字符串并从左到右查找正则表达式。

From what you have mentioned, I understand that you simply want to separate numbers from the operators, assuming that you have a well constructed input string.根据您所提到的,我知道您只是想将数字与运算符分开,假设您有一个构造良好的输入字符串。 In that case, the following code may help:在这种情况下,以下代码可能会有所帮助:

public class OperatorsAndNumbers{
    static List<String> parts = new ArrayList<>();
    public static void main( String[] args ){
        String str = "10+10+10";
        Pattern p = Pattern.compile( "(\\d+)|([+-])" );

        /* Run the loop to match the patterns iteratively. */
        Matcher m = p.matcher( str );
        while( m.find() ) {
            handle( m.group() );
        }

        System.out.println( parts );
    }

    /** Do whatever is to be done with detected group. You may want to add them to separate lists or
     * an operation tree, etc. In this example, it simply adds it a list. */
    private static void handle( String part ){
        parts.add( part );
    }

}

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

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