繁体   English   中英

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

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

我的目标是迭代一个字符串并提取某些字符的实例。

理想情况下,我想使用模式和匹配器。

例如。

String str = "10+10+10";

如果我想制作一个代码来检测字符串的一部分是数字还是 + 运算符,然后将字符串的那部分保存在数组中,具体取决于它的内容,然后移动,我该怎么做到下一个角色?

我知道我应该使用正则表达式,但不完全是我应该如何遍历字符串并从左到右查找正则表达式。

根据您所提到的,我知道您只是想将数字与运算符分开,假设您有一个构造良好的输入字符串。 在这种情况下,以下代码可能会有所帮助:

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