【问题标题】:Iterating over string. Searching for special characters. Using regular expressions遍历字符串。搜索特殊字符。使用正则表达式
【发布时间】:2020-01-29 07:58:48
【问题描述】:

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

理想情况下,我想使用 Pattern 和 Matcher。

例如。

字符串 str = "10+10+10";

如果我想编写一个代码来检测字符串的一部分是数字还是 + 运算符,然后根据字符串的内容将字符串的那一部分保存在数组中,我该怎么做?然后继续移动到下一个字符?

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

【问题讨论】:

  • 如果你说的是整数,那么\d+|\+ 可能会依次匹配所有数字和加号运算符。
  • 你能举一个预期输出的例子吗,不确定我是否完全理解这个问题

标签: java regex pattern-matching


【解决方案1】:

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

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 );
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2019-10-17
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多