Return numbers from a String

Asked

Viewed 58 times

1

I am a programmer PHP and giving maintenance on a project Java I found myself with the need to return only numbers contained in a certain String.

I found no questions about it in Sopt and found in Soen, so I bring here this question seeking to know what is the best option, since in Java for being a lower level language, everything or almost everything makes a difference in processing and can always be optimized...

An example of what I am requesting:

String cnpj = "83.411.122/0001-06";

The expected return:

"83411122000106"
  • 2

    You can give us an example of what you mean by "[...] returning only numbers in a given one String"? On a parallel subject Java is a commercial language, it is far from low level.

  • Okay, let’s get things straight, Low Level, which means she has more power over the hardware, more ability to manipulate it, secondly, I’ll put an example of what I’m suggesting, sorry I’m not exactly clear, buddy.

  • @Genos, I think it’s clearer now.

1 answer

3


Solution found in Soen:

str = str.replaceAll("\\D+","");
  • In this case he could also use regular expression to find only variable numbers String and then return what had entered, right?

  • Sorry @R.Santos, I didn’t quite understand your question, in this case the replaceAll with Regular Expression already returns String only with numbers...

  • It’s just that when I used regular expressions, I used matcher and pattern to stipulate patterns of what I would like to select in a text, in which case it would create a regular expressions that looked only for numbers, and that after analyzing the String return to me what had been found

Browser other questions tagged

You are not signed in. Login or sign up in order to post.