Solved

How do I extract a number from a Java string?

Posted on 2012-04-05
5
333 Views
Last Modified: 2012-04-06
I have the following string in Java:

"Send data to port 2112 with this entire message intact"

What is a good way to extract the number from the string and place "2112" in an integer?

I know some "brute force or hard" ways to do this but I am looking for something that uses good Java programming techniques.

What I am actually doing here is testing that ports are available---so i send a message to a server on port 2112 and tell it to send me back the same message on the specified port.
0
Comment
Question by:cschene
  • 2
  • 2
5 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 37814599
If there's only one:

String s = "Send data to port 2112 with this entire message intact";
String n = s.replaceAll("\\D", "");
int i = Integer.parseInt(n);

Open in new window

0
 

Author Comment

by:cschene
ID: 37814770
Works great! Thanks!
0
 

Author Closing Comment

by:cschene
ID: 37814772
Fast response!
0
 

Expert Comment

by:kamalakardandu
ID: 37814982
Good Answer....
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37815564
:)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Understanding FTPS File transfer is a common requirement in most Enterprises. While there are numerous ways to get a file from Point A to Point B over a network, perhaps the most common method still in use is FTP – File Transfer Protocol. FTP is …
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now