Link to home
Start Free TrialLog in
Avatar of apparition
apparition

asked on

String Manupulation.

In a string whenever the charcters "DC#" appears, I want to extract the next 4 characters.
So for example, if the string was "LAWRENCE DC#1234 MORE TEXT" I want to extract "1234".
How can this be done ?
Avatar of cjjclifford
cjjclifford

split the string on the '#' and take the first 4 characters of the second section of the split...

mystring.split( "#" ).substring( 0, 4 )
Avatar of apparition

ASKER

I need to make sure the "#" is preceded by "DC"
so if my string was  "BLA # BLA DC#1234 BLA" your solution won't work.
sorry, of course split() returns array, and also, substring() takes the second argument as the index to stop the substring, so 3 will be the fourth character...

so...

mystring.split( "#" )[1].substring( 0, 3 )
ASKER CERTIFIED SOLUTION
Avatar of cjjclifford
cjjclifford

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
again won't work for a string like  "BLA # BLA DC#1234 BLA"
thanks - out of interest, the regex impl is along the following lines:

import java.util.regex.*;
...
Matcher matcher = Pattern( ".*DC#(....).*" ).matcher( mystring );
if( matcher.matches() ) {
    substring = matcher.group(1);
}