Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a solution that uses <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html" rel="nofollow noreferrer"><code>java.util.Scanner</code></a>:</p> <pre><code>Scanner sc = new Scanner("12+3 - 456").useDelimiter("\\b"); while (sc.hasNext()) { if (sc.hasNextInt()) { int num = sc.nextInt(); System.out.printf("Got an int [%s]%n", num); } else { String op = sc.next().trim(); System.out.printf("Got an op [%s]%n", op); } } </code></pre> <p>The above prints (<a href="http://ideone.com/MMvJn" rel="nofollow noreferrer">as seen on ideone.com</a>):</p> <pre><code>Got an int [12] Got an op [+] Got an int [3] Got an op [-] Got an int [456] </code></pre> <p>The delimiter is <code>\b</code> (the backslash doubled in a Java string literal), which is the "word boundary". It occurs, among other places, between word characters <code>\w</code> (which digits are) and non-word characters <code>\W</code> (which operators are).</p> <p>As a caveat, this delimiter regex will not properly tokenize floating point numbers with decimal points, but more specific regex can be written to address those issues should they be needed.</p> <p>Note also the convenience of using <code>Scanner</code> to parse the <code>String</code> into <code>int</code>; you can do this in such a way that it will never throw an exception (e.g. by first asserting that it <code>hasNextInt()</code>).</p> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner">Validating input using java.util.Scanner</a> - a quick <code>Scanner</code> tutorial</li> </ul> <h3>References</h3> <ul> <li><a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow noreferrer">regular-expressions.info/Word Boundaries</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload