how to extract substring

  • Thread starter Petterson Mikael
  • Start date
P

Petterson Mikael

Hi,

I have the following string (read from a file).

} lrsstuv;

I need to extract the lrsstuv part. The bracket will always be there.
The number of spaces after the bracket varies. And at last the ';' is
always after there after the name. Any hints on how to do this?

I am using jdk 1.4

cheers,

//mikael
 
D

derek

I have the following string (read from a file).
} lrsstuv;

I need to extract the lrsstuv part. The bracket will always be there.
The number of spaces after the bracket varies. And at last the ';' is
always after there after the name. Any hints on how to do this?

String s = "} lrsstuv;";
String result = s.substring(1, s.length()-1).trim();
 
S

Simon

I have the following string (read from a file).
} lrsstuv;

I need to extract the lrsstuv part. The bracket will always be there.
The number of spaces after the bracket varies. And at last the ';' is
always after there after the name. Any hints on how to do this?

try to match it against a regular expression? Try something like

}\s*(\w+);

(no guarantee for escape characters...)
Look into the documentation for java.util.regex.Pattern.

If you are sure that the "}" and ";" are really there, you can also use
s.substring(1, s.length()-2).trim() to remove "}" and ";" and then remove the
blanks. That could be easier.
 
P

Petterson Mikael

Simon said:
try to match it against a regular expression? Try something like

}\s*(\w+);

(no guarantee for escape characters...)
Look into the documentation for java.util.regex.Pattern.

If you are sure that the "}" and ";" are really there, you can also use
s.substring(1, s.length()-2).trim() to remove "}" and ";" and then remove the
blanks. That could be easier.

Last works like a charm ;-)

cheers,

//mikael
 
S

Simon

If you are sure that the "}" and ";" are really there, you can also use
No, it does not. It also removes the last character, in your case the 'v'.
It should be '-1' instead of '-2'.

You are right, sorry. Second argument is endIndex, not length.
 
P

Petterson Mikael

Simon said:
You are right, sorry. Second argument is endIndex, not length.

Yeah I know but that part was so simple that I could change it myself. :)

cheers,

//mikael
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top