Reg: String splitting

Hi,
I have a string like title-name.
i want to capture only title into another string.
how can i do it. kindly suggest.

Hi Prasanthi
You can either of the following code, for spliting and capturing the string.
1.
StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         wdComponentAPI.getMessageManager().reportSuccess(st.nextToken());
2.
class StringSplit {
  public static void main(String args[]) throws Exception{
      new StringSplit().doit();
  public void doit() {
      String s3 = "Real-How-To";
      String [] temp = null;
      temp = s3.split("-");
      dump(temp);
  public void dump(String []s) {
    wdComponentAPI.getMessageManager().reportSuccess("----
    for (int i = 0 ; i < s.length ; i++) {
        wdComponentAPI.getMessageManager().reportSuccess(s<i>);
    wdComponentAPI.getMessageManager().reportSuccess("----
Thanks
Anup

Similar Messages

  • Java.lang.string(split)

    I am trying to split a delimited input record using the Perl equivalent pattern of /\|/. Can someone tell me what that translates too exactly in Java? My guess is "//'\'|//".
    Also once I split to an array I would like to pull the contents of each field out individually. The string.split function appears to place the entire record in the array. I am using the following syntax with
    the bufferedReader:
    String[] RecFields = thisLine.split("//'\'|//");
    My understanding was that this would place each field in it's own Array element without saving the delimeter. So that I could retrieve field
    number 3 in it's entirety for example by using the syntax:
    String strField3 = RecFields[3];
    StringTokenizer has already been tried and will not work because of null (empty) values in the string are skipped as Array elements.

    That was it!!! It was the actual delimiter string. I thought the extra slashes were an "OR" statement to eliminate duplicate records. I'll have to get this confirmed with Perl though. It's working perfectly now with \\| as the delimiter string. For those of you who are curious it was a 20 field pipe delimited record. Each field hada a variable length. The only records with values in each field all the time were fields 1 & 2, the others can contain null values. However all 20 fields are delimited no matter what value they contain.
    Thanks for your help everyone!

  • Faster split than String.split() and StringTokenizer?

    First I imrpoved performance of split by replacing the String.split() call with a custom method using StringTokenizer:
                    final StringTokenizer st = new StringTokenizer(string, separator, true);
                    String token = null;
                    String lastToken = separator; //if first token is separator
                    while (st.hasMoreTokens()) {
                        token = st.nextToken();
                        if (token.equals(separator)) {
                            if (lastToken.equals(separator)) { //no value between 2 separators?
                                result.add(emptyStrings ? "" : null);
                        } else {
                            result.add(token);
                        lastToken = token;
                    }//next tokenBut this is still not very fast (as it is one of the "hot spots" in my profiling sessions). I wonder if it can go still faster to split strings with ";" as the delimiter?

    Yup, for simple splitting without escaping of separators, indexOf is more than twice as fast:
        static private List<String> fastSplit(final String text, char separator, final boolean emptyStrings) {
            final List<String> result = new ArrayList<String>();
            if (text != null && text.length() > 0) {
                int index1 = 0;
                int index2 = text.indexOf(separator);
                while (index2 >= 0) {
                    String token = text.substring(index1, index2);
                    result.add(token);
                    index1 = index2 + 1;
                    index2 = text.indexOf(separator, index1);
                if (index1 < text.length() - 1) {
                    result.add(text.substring(index1));
            }//else: input unavailable
            return result;
        }Faster? ;-)

  • Problem using java String.split() method

    Hi all, I have a problem regarding the usage of java regular expressions. I want to use the String.split() method to tokenize a string of text. Now the problem is that the delimiter which is to be used is determined only at runtime and it can itself be a string, and may contain the characters like *, ?, + etc. which are treated as regular expression constructs.
    Is there a way to tell the regular expression that it should not treat certain characters as quantifiers but the whole string should be treated as a delimiter? I know one solution is to use the StringTokenizer class but it's a legacy class & its use is not recommended in Javadocs. So, does there exist a way to get the above functionality using regular expressions.
    Please do respond if anyone has any idea. Thanx
    Hamid

    public class StringSplit {
    public static void main(String args[]) throws Exception{
    new StringSplit().doit();
    public void doit() {
    String s3 = "Dear <TitleNo> ABC Letter Details";
    String[] temp = s3.split("<>");
    dump(temp);
    public void dump(String []s) {
    System.out.println("------------");
    for (int i = 0 ; i < s.length ; i++) {
    System.out.println(s);
    System.out.println("------------");
    Want to extract only string between <>
    for example to extract <TitleNo> only.
    any suggestions please ?

  • How to implement String.split() on 1.3?

    Hi,
    I have a String split method which is able to be run on 1.4.
    The string "boo:and:foo", for example, yields the following results with these parameters:
    Regex Limit Result
    : 2 { "boo", "and:foo" }
    : 5 { "boo", "and", "foo" }
    : -2 { "boo", "and", "foo" }
    o 5 { "b", "", ":and:f", "", "" }
    o -2 { "b", "", ":and:f", "", "" }
    o 0 { "b", "", ":and:f" }
    The program cannot be complied if I run it on 1.3. How can I do the 1.4 split function on 1.3?
    Thanks for advice

    If you don't require the more powerful regular expression matching, you can implement the split() functionality with existing String methods.
    If you are splitting around a character, you can use StringTokenizer, unless you care about empty tokens. If you need empty tokens returned, then you can use the following method:
    public static String[] split(String input, char c) {
        int tokenCount = 0;
        int cIndex = -1;
        do {
            cIndex = input.indexOf(c, cIndex + 1);
            tokenCount++;
        } while (cIndex >= 0);
        String[] tokens = new String[tokenCount];
        int tokenIndex = 0;
        do {
            int index = input.indexOf(c, cIndex + 1);
            if (index < 0) {
                tokens[tokenIndex] = input.substring(cIndex + 1);
            else {
                tokens[tokenIndex] = input.substring(cIndex + 1, index);
            cIndex = index;
            tokenIndex++;
        } while (cIndex >= 0);
        return tokens;
    }If you need to split around a multiple character string, use the following method.
    public static String[] split(String input, String str) {
        int strLength = str.length();
        int tokenCount = 0;
        int strIndex = -strLength;
        do {
            strIndex = input.indexOf(str, strIndex + strLength);
            tokenCount++;
        } while (strIndex >= 0);
        String[] tokens = new String[tokenCount];
        int tokenIndex = 0;
        strIndex = -strLength;
        do {
            int index = input.indexOf(str, strIndex + strLength);
            if (index < 0) {
                tokens[tokenIndex] = input.substring(strIndex + strLength);
            else {
                tokens[tokenIndex] = input.substring(strIndex + strLength, index);
            strIndex = index;
            tokenIndex++;
        } while (strIndex >= 0);
        return tokens;
    }These have only been lightly tested, no guarantees.

  • How to use method String.split

    I am spliting a string, just like "1a|24|3|4". My code is
    String[] array = new String[10];
    String buff = "1|2|3|4";
    array = buff.split("|");
    System.out.println(array[1]);
    I think that the result should be "24", but the result always
    is "1". Why? When I use String.split(",") to split a string "1a,24,3,4",
    I can get the result "24". Can't "|" be used as a delimiter? Who can
    explain this issue? Thanks.

    Hi
    The argument of split is a "regular expression" instead any common string with delimiters as used in StringTokenizer.
    The char "|" is named as "branching operator" or "alternation"..doesn't matter this moment.
    If you must to use "|" in source strings, change the regular expression to "\\D", it means "any non numeric char":
    // can use any delimiter not in range '0'..'9'
    array = buff.split("\\D");
    Regards.

  • Regular expression not working for String.split()?

    hi, i have a String variable called 'table'.
    It has a bunch of chunks of data seperated by whitespace, whether it
    be spaces or carraige returns. Anyways, i want to split this up using
    the String.split function. i want to split it around whitespace.
    here is my code:
    String codes[] = table.split("\s");
    However, i'm getting back all nulls in the codes variable. What am i doing wrong?
    thanks

    split("\\s")\ is special both in Java String literals and in regex, so you need two of them.
    You'll probably also have to take an extra step it you don't want regex to stop at newlines. I forget the details, so check the docs.

  • String split problem around | character

    I'm trying to split a string (well, a bunch of them--astronomical data) into an array of substrings around a common character, the |. Seems pretty simple, but the regular String.split() method doesn't work with it. Here's part of the code I tried (more or less):
    String line = "";
                String[] blah = new String[43];
                //do {
                    line = inputStream.readLine();
                    if (line != null)
                        blah = line.split("|");Reading the line from the input stream gives you a string like so:
    0001 00008 1| | 2.31750494| 2.23184345| -16.3| -9.0| 68| 73| 1.7| 1.8|1958.89|1951.94| 4|1.0|1.0|0.9|1.0|12.146|0.158|12.146|0.223|999| | | 2.31754222| 2.23186444|1.67|1.54| 88.0|100.8| |-0.2
    Basically a long list of data separated by |. But when I split the string around that character, it returns an array of each individual character, where blah[1] is 0, blah[4] is 1, etc. The split function works fine for other expressions, I tried it (using "5" as the expression gives 0001 00008 1| | 2.317 as the first string, for example), so what's wrong? How do I split around the |?

    confusing, the split method takes a regular expression, and as such, the "pipe": |, is a special char for a regexp.
    you need to escape it (in regex-style context), via:message.split("\\|");

  • String.split() regular expression

    Regular expression escapes me. I have a line of a CSV file that looks like this:
    1,,3,2,45.00,"This & That, LLC",0
    I want the string split by commas but the problem with the line above is there's a comma in the name of the company...I obviously don't want the company name split in half...what would the regular expression be that I would provide to the split method to ensure that only commas not found in between double quotes are used to split the string into an array of Strings? is this possible?
    Thanks in advance!
    Rob

    Telling someone to google might be deserved, but it is mean and unhelpful.
    If you want to find a regex for CSV's see O'Reilly's "Mastering Regular Expressions" Section 8.4.4.3. Either buy the book - it's worth it - or subscribe to safari.

  • Is String.split() multithreaded internally

    Hi,
    Can anyone tell me whether String.split() method is multi-threaded or not?
    Whether it internally creates threads??

    The definitive answer will be found in the Java source code, you should look there for the answer.
    If you are asking "does String.split() make use of multiple CPUs" then the answer is very probably not.
    Making use of multiple CPUs seem to be the only likely reason to make a "mult-threaded" version.
    If you are asking "is String.split() thread safe" then the answer is most probably yes.
    Strings are immutable so cannot be 'damaged' by multiple threads.
    If you expose the result array to multiple threads, which can write to it, then of course you are asking for trouble,
    but this in itself has nothing to do with the implementation of String.split()

  • Problems with String.split(regex)

    Hi! I'm reading from a text file. I do it like this: i read lines in a loop, then I split each line into words, and in a for loop I process ale words. Heres the code:
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line;
    while ((line = reader.readLine()) != null) {
        String[] tokens = line.split(delimiters);
        for (String key : tokens) {
    doSthToToken();
    reader.close();The problem is that if it reads an empty line, such as where is only an "\n", the tokens table has the length == 1, and it processes a string == "". I think the problem is that my regex delimiters is wrong:
    String delimiters = "\\p{Space}|\\p{Punct}";
    Could anybody tell me what to do?

    Ok, so what do you suggest?I suggest you don't worry about it.
    Or if you are worried then you need to test the two different solutions and do some timings yourself.
    And how do you know the regex lib is so slow and badly written?First of all slowness is all relative. If something takes 1 millisecond vs 4 milliseconds is the user going to notice? Of course not which is why you are wasting your time trying to optimize an equals() method.
    A general rule is that any code that is written to be extremely flexible will also be slower than any code that is written for a specific function. Regex are used for complex pattern matching. StringTokenizer was written specifically to split a string based on given delimiters. I must admit I haven't tested both in your exact scenario, but I have tested it in other simple scenarios which is where I got my number.
    By the way I was able to write my own "SimpleTokenizer" which was about 30% faster than the StringTokenizer because I was able to make some assumptions. For example I only allowed a single delimiter to be specified vs multiple delimiter handled by the StringTokenizer. Therefore my code could be very specific and efficient. Now think about the code for a complex Regex and how general it must be.

  • Arraylist and string split help

    i want to add items from a textfile into an array list here is the txt file
    Title,Artist
    tester,test
    rest,test
    red, blue
    here is the code i am using
    try{
      FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);
    String s;
    int c = 0;
    while((s = br.readLine()) != null) {
      c=c+1;
      CD c3 = new CD("");
      String tokens[] = s.split(",");
            for(String token : tokens) {
          System.out.println(c);
           System.out.println(tokens.toString());
              if ( c == 2){
                c3.setTitle(token);
                    System.out.println(c);
                     System.out.println(token);
             c = c+1;
                  if ( c == 3 ){
                    c3.setArtist(token);
                    discsArray.add(c3);
                      System.out.println(token);
                    c = 1;
              System.out.println(token); }}
    fr.close();
    }catch (Exception e){
          System.out.println("exception occurrred");
      }here is the output of the array
    title: tester artist: tester title: rest artist: tester title: red artist: red
    as you can see it misses the last line of the textfile and also doesnt display all of the separated string;
    thanks any help is appreciated

    thanks for ur help but that wasnt the problem
    i have fixed it however when its read all the lines
    an exception is always thrown
    everything works just crashes at the end
    any ideas
    try{
      FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);
    String s;
    int c = 0;
    while((s = br.readLine()) != null) {
      c=c+1;
      CD c3 = new CD("");
      String tokens[] = s.split(",");
            for(String token : tokens) {        
              if ( c == 2){
                c3.setTitle(token); 
                      c = c+1;
              if ( c == 3 ){
                    c3.setArtist(token); 
           if ( c == 3 ){
                    discsArray.add(c3);
                    c = 1; 
    fr.close();
    br.close();
      }catch (Exception e){
          System.out.println("exception occurrred");
      }

  • What's rong wiht String.split(".")?

    Hi all
    I have two similar code below:
    public class Test {
        public static void main(String[] args) {
            String ip  = "192,168,30,153";//comma
            String[] ss = ip.split(",");   //it's comma
            for(String s:ss){
                 System.out.println(s);
    }the result is :
    192
    168
    30
    153
    but when it changs to period nothing printed.
    public class Test {
        public static void main(String[] args) {
            String ip  = "192.168.30.153";//period
            String[] ss = ip.split(".");   //it's period
            for(String s:ss){
                 System.out.println(s);
    } thanks

    .is the regex character that means "any character". If you want to split on a literal period, you need to escape it.
    \\.

  • String Splitting

    hi
    if i/p string is 185 the existing query is splitting 92 characters,space and remaining characters(which is greater than 80).
    this query is working fine if i/p string length is below 160 since the splitted strings length would be less than 80.
    i require a query which would break 185 string in two or three strings but length of each string should be less than 80.
    exiting query that i am using
    select substr(s_string, 1, trunc(length(s_string) / 2)) || ' ' ||
    substr(s_string, trunc((length(s_string / 2))) + 1) from dual;

    an example would be if there are no space involved:
    SQL> Create Or Replace Function fnc_string_split (pPosition Number,
      2                                               pString   Varchar2) Return Varchar2 is
      3    vSplit     Varchar2(2000);
      4    vStrLen    number := 0;
      5    vStrDiv    number := 0;
      6  Begin
      7    vStrLen := Length(pString);
      8    vStrDiv := Trunc(vStrLen/pPosition);
      9    If vStrDiv > 1 Then
    10      For i in 1..vStrDiv Loop
    11        If i = 1 Then
    12          vSplit := substr(pString,1,pPosition * i);
    13        Else
    14          vSplit := vSplit ||' '|| substr(pString,pPosition * i, pPosition);
    15        End If;
    16      End Loop;
    17    End If;
    18    Return (vSplit);
    19  End;
    20  /
    SQL> select * from string_values;
    COL1
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    SQL> select fnc_string_split(80,col1) split
      2    from string_values;
    SPLIT
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA A
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAA
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    AA A
    SQL>

  • How to ingore the , within ( ) when i do String.split(",")??

    hi guys,
    i am currently using java class to read CSV files.
    my example code is
    String str = dataFile.readLine();
    String[] words = str.split (",");
    i do not wish to take the , within brackets to be splitted up as in (today,tomorrow), after splitting them i still want them to stick as (today,tomorrow).
    for example if the above String str is "(today,tomorrow),yesterday,nextday
    after splitting i want the output to be:
    (today,tomorrow)
    yesterday
    nextday
    is it possible to do it? anyone help?? thanks!

    Java does not have an API to do this, also its not fair to ask that. You may need to write your own code to do it. I think its simple as well.
    First split on "," and then pass through the array and form the string if the string startswith "(" by appending the next strings untill u get a string which ends with ")".
    VJ

Maybe you are looking for