Java regex help (splitting strings)

Associate
Joined
19 Jun 2006
Posts
162
Location
Swansea, Wales
Hi people,

I want to split up a string and I think regex is probably the best way to do it but not sure and would like some help.

The string is an SDP media attribute [link] and i need to get the port number so if i have the following string...

m=audio6000RTP/AVP0

I want to get the "6000" bit. The number following m=audio will always be the port number so i just to to look character by character after m=audio for numbers 0-9 until i find a letter a-z.

Ideas? :confused:
 
Will the string always start with m=audio6000RTP/AVP0?

Code:
String smallerBits = line.subString(7, line.length); // line = m=audio...
String[] lulz = smallerBits.split("RTP");
int portNumber = Integer.parseInt(lulz[0]);

There's probably a more elegant way to do it with a regex though.
 
Code:
String toSearch = "m=audio6000RTP/AVP0";
java.util.regex.Pattern p = java.util.regex.Pattern.compile("[^m=audio][0-9]*[^a-zA-Z/]");
java.util.regex.Matcher m = p.matcher(toSearch);
if(m.find()){
   int port = Integer.parseInt(toSearch.substring(m.start(), m.end()));
}

port=6000 \o/
 
If you just want to find the 6000, then this would work:

Code:
String string = "m=audio6000RTP/AVP0";
String newString = string.substring( string.indexOf('o')+1, string.indexOf('o')+5);
System.out.println(newString);

However, if the length of port numbers will be different, then code posted before will do a better job :)
 
Back
Top Bottom