gpt4 book ai didi

java - 迭代字符串。搜索特殊字符。使用正则表达式

转载 作者:行者123 更新时间:2023-12-01 18:39:41 26 4
gpt4 key购买 nike

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

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

例如。

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

}

关于java - 迭代字符串。搜索特殊字符。使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59962690/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com