Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I am sure regex and parseInt will perform well enough for you. However for your interest, I have compared it with a simple loop.</p> <pre><code>public static final Pattern DIGITS = Pattern.compile("(\\d+)"); public static void main(String[] args) { String text = "Some text before a number 123456 and some after"; for (int i = 0; i &lt; 5; i++) { timeRegex(text); timeLooping(text); } } private static int timeLooping(String text) { int ret = 0; final int runs = 1000; long start = System.nanoTime(); for (int r = 0; r &lt; runs; r++) { for (int i = 0; i &lt; text.length(); i++) { char ch = text.charAt(i); if (ch &lt;= '9' &amp;&amp; ch &gt;= '0') ret = ret * 10 + ch - '0'; else if (ret &gt; 0) break; } } long time = System.nanoTime() - start; System.out.printf("Took %,d ns to use a loop on average%n", time / runs); return ret; } private static int timeRegex(String text) { int ret = 0; final int runs = 1000; long start = System.nanoTime(); for (int r = 0; r &lt; runs; r++) { Matcher m = DIGITS.matcher(text); if (m.find()) ret = Integer.parseInt(m.group()); } long time = System.nanoTime() - start; System.out.printf("Took %,d ns to use a matcher on average%n", time / runs); return ret; } </code></pre> <p>prints</p> <pre><code>Took 19,803 ns to use a matcher on average Took 85 ns to use a loop on average Took 12,411 ns to use a matcher on average Took 83 ns to use a loop on average Took 8,199 ns to use a matcher on average Took 79 ns to use a loop on average Took 11,156 ns to use a matcher on average Took 104 ns to use a loop on average Took 4,527 ns to use a matcher on average Took 94 ns to use a loop on average </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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