Using String.split..

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 ?

BoBear2681 wrote:
import java.util.regex.*;
public class Deleteme {
     public static void main(String[] args) {
          String input = "Dear <TitleNo> \n ABC Letter <Address name> Details";
          Pattern p = Pattern.compile("<(.+)>");
          Matcher m = p.matcher(input);
          while (m.find()) {
               System.out.println(m.group(1));
I hope you wanted that to return "TitleNo> \n ABC Letter <Address name", because that's what you just matched. You need to either use the non-greedy .+? or match [^>]+Edited by: DeltaGeek on Feb 27, 2008 1:49 PM

Similar Messages

  • 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.

  • 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 ?

  • 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? ;-)

  • How to use two split this method in my code

    How to use two split this method in my code
    if i got one string line which like this
    ("aa!bb!cc~ab!bc!cd") a
    nd want to use two split to spare ! and ~ this seal for my spare point how that output
    has come diff ?
    public static void main(String[] args) {
        String str = "aa!bb!cc~ab!bc!cd";
        String strs[]= str.split("~");
        String strE[]= str.split("!");
        int count =0;
        for(int j=0; j < strs.length; j++){
          for (int i = 0; i < strE.length; i++){   
              System.out.println(count + " " + strE);
    count++;
    the output how can it be like this
    0 aa
    0 bb
    0 cc
    1 ab
    1 bc
    1 cd

    Move your second slit inside the first loop, so you are splitting the substring, not the entire string.

  • Using String Tokenizer in constructors

    Hi there,
    I am supposed to create a constructor name called Abbreviation (String abbrName, String fullName).
    and Im given a list of abbreviation and their full name as followed in a text file: eg:
    US - United States
    UK - United Kingdom
    How do I initialize the objects using the Abbreviation class?
    I have done some codings, please do take a look:
    public Abbreviation(String abbrName, String fullName)
                   this.abbrName = abbrName;
                   StringTokenizer strToken = new StringTokenizer(fullName, "- ");
                   //how do I count the number of abbreviation and stored them in a array ?
    Thanks..

    You need to create a new instance of your Abreviation class for each line you read from the file, so you can't read the file in the constructor. The constructor gets called for each instance of the class you create.
    I wouldn't recommend StringTokenizer here, unless it's specified in your project. There are various ways you could try. I suggest you read up on String.split(), and regular expressions. (you might use the java.util.regexp.Pattern class).
    Also read up on ArrayList.

  • 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.

  • String splitting with regular expressions

    Hello everyone
    I need some help in splitting the string using regular expressions
    Suppose my String is : abc def "ghi jkl mno" pqr stu
    after splitting the reulsting string array should contain the elements
    abc
    def
    ghi jkl mno
    pqr
    stu
    what my regular expression should be

    Since this is essentially the same as parsing CSV data, you might want to download a CSV parser and adapt it to your need. But if you want to use regexes, split() is not the way to go. This approach should work for your sample data:
    Pattern p = Pattern.compile("\"[^\"]*+\"|\\S+");
    Matcher m = p.matcher(input);
    while (m.find())
      System.out.println(m.group());
    }

  • 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()

  • How to Use String Patterns?

    Hai all,
    I need help, In my project i am using String patterns.
    i need to search a string which contains special characters.
    Ex:
    1.Abstract{meaning}
    I have to search Abstract in this case.
    Another case is:
    2.Moon
    in this i Have to search Moon and
    so on.
    For this Source Code I had written is:
    string input = args[0];
    String pattern = "[0-9].*+\\{*\\}";
    String pattern1 = "[0-9].*";
    string line = "1.Abstract{meaning}";
    string line1 = "1.Moon";
    if( (Pattern.matches(pattern, line))||(Pattern.matches(pattern1, line1)) )
    Pattern p = pattern.compile("\\.");
    Pattern p1 = pattern.compile("\\{");
    String[] tokens = p.split();
    String[] tokens1 = p1.split();
    for(int i = 0; i < tokens.length ; i++)
    for(int j = 0; j < tokens1.length ; j++)
    if((tokens.equals(input))||(tokens[j].equals(input)))
    System.out.println(tokens[i]);
    System.out.println(tokens[j]);
    in this code it matching the 2nd case. it is not matchinf the 1st case.
    please help me.
    Thanks

    look up for "Using formatters" in the FB help.
    Essentially you'll instantiate a format, NumberFormatter for
    numbers for example, and set it's properties like e.g. showing a
    thousand separator and then one some event of the TextInput --
    valueCommit for example -- you'll do something like:
    ti.text = nf.format(ti.text)
    this is would also give you opportunity to validate user
    input using the same formatter and valid event.
    ATTA

  • Special characters in XML structure when prepared using String

    Hi,
       I am preparing an XML structure using 'String'. I print the prepared XML structure in the server log. Issue is that I am seeing extra characters([[ and ]]) that I am not printing.
    Please let me know how to get rid of those.
    Code Excerpt
            String xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            String lsb_xmlcon = xmlHeader;
            logger.info("ReqXMLString Process  1  --->" + lsb_xmlcon);
            lsb_xmlcon = lsb_xmlcon +("\n");
            logger.info("ReqXMLString Process  1.1  --->" + lsb_xmlcon);
            lsb_xmlcon = lsb_xmlcon +("<REQUEST>");
            lsb_xmlcon = lsb_xmlcon +("\n");
            logger.info("ReqXMLString Process  1.2  --->" + lsb_xmlcon);
    Log
    ReqXMLString Process  1  ---><?xml version="1.0" encoding="utf-8" ?>
    ReqXMLString Process  1.1  ---><?xml version="1.0" encoding="utf-8" ?>[[
    ReqXMLString Process  1.2  ---><?xml version="1.0" encoding="utf-8" ?>[[
    <REQUEST>
    Thanks,
    Message was edited by: 996913
    This issue is observed only while running the code in server, not from Jdev.
    When we append the additional tags without new line character, "\n", there are no extra characters being added. Also, in other case also. where we used "Marshaller" to prepare the XML, we have seen this issue.
    After we set the below property to false, we got rid of the extra characters.
                            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    Apparently the insertion of new line when the code runs on server(Weblogic 10.3.6.0) is creating the issue.
    Please let me know if anyone has come across a similar scenario.
    Thanks,

    I am building this XML in a servlet so ,right, DOM does process XML (even though a valid HTML file can be loaded into a DOM object) but if you build XML using DOM then write the XML out using PrintWriter and Transformer objects this will cause the XML to print out in your browser. If you view source on this XML you will see that the DOM object has translated all special characters to there &xxxx; equivalent. For a example: when the string (I know "cool" java) gets loaded into a attribute using the DOM object then wrote back out it looks like (I know &xxx;cool&xxx; java) if you view the source in your browser. This is what it should do, but the DOM object is not change the � to the "&xxxxx;". This servlet is acting as a gateway between a Java API and a windows asp. The asp will call the servlet expecting to get XML back and load it directly into a DOM object. When the windows DOM object gets the xml that I am returning in this servlet is throws a exception "invalid character" because the � was not translated to &xxxx; like the other characters were. According to the book HTML 4 in 24 hours (and other references) the eacute; or #233; are how you say "�" in HTML or XML. How do you say it?

Maybe you are looking for

  • Safari crashes on pages made with iWeb

    Hi there, does someone have an idea on the route cause, please? As well, Safari crashes on homepages made with iWeb or pages using flash - even latest adobe update were sucessful installed. FYI - restart Safari or reinstall does not reflect any chang

  • Query Builder won't apply chosen date to the where clause

    Does anybody know why when I chose a date field, in the where clause, when using Query Builder, it won't actually write the chosen date to the actual query? If I select the "View Query" tab, no date shows up. Also if I press the "Run Report" button i

  • Mass upload of Object Services to material master - Create Document (URL)

    Hi there, Does anyone have any experience of uploading URL's to material masters via object services. Can we use LSMW? I have tried to record the transaction, however, this excludes the object services button Any feedback greatly appreciated Steve

  • #ERR:75-Path/File access error

    Hi folks, Trying to build a report using the EVDRE data grid and upon dragging & dropping the object to the report display area, this error message  "#ERR:75-Path/File access error"  is showing up.  Please can anyone provide an explanation for this.

  • I need a "hide" script for Microsoft Excel

    Hi. I just "upgraded" everything, new Intel based Macbook Pro, and Office 2008 for Macs. Why did I upgrade? Good question! Anyways, when I used Office 2004 for macs, I used a macro to hide several rows so that I could view information in a condensed