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";
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 );
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.