How to split a string with regular expression

Hi.
I need to split a string with a regular expression.
Example
String = "this is; a test";rune haavik;12345;
And I want the output to be:
"this is; a test"
rune haavik
12345
If I use this code:
private void test1()
String str = "\"this is; a test\";rune haavik;12345;";
int i=0;
String[] tmp = str.split(";");
while(i<tmp.length)
System.out.println(tmp);
i++;
Then it splits also in the "" text.
Regards
Rune haavik

Rune haavik:
The most effective way to achieve the end result is, I believe, to read the characters one by one, using a flag that indicates if we are inside quotation or not.
Well, if we are in a mind game, then the following should do.
       String[] tmp = str.split(";(?![^\"]*\";)");

Similar Messages

  • How to split a string with linefeed character ( LF ) as a delimiter in VB6?

    Hi. I am writing a small program in VB 6.0. 
    I have a string named Data and it contains few characters along with <LF> in it. ( <LF> is a new line/line feed character).
    I want to split this string with <LF> as delimiter and store the tokens in an array. I tried with split function and its giving me type mismatch error. Can anyone tell me how to do it?
    I am giving the pseudo-code below.
    Dim Data as string
    Data = "hello, how are you<LS>good morning guys <LS> hi"
    Dim strarray() as stringMsgbox(Data)
    strarray = split(Data, "<LS>")
    When i see the Data in message box before split function, it shows up in different lines like this:
    hello, how are you
    good morning   guys 
    hi
    I want the final array strarray to be like this:   strarray(0) = "hello, how are you"
    strarray(1) = "good morning   guys "
    strarray(2)  = " hi"
    The spaces can be as it is. Just i need the string to be delimited wherever <LS> is there.
    Please help me as soon as possible. Though it is small one, i am stuck here.
    Thanks in advance,
    Satya.

    Hello,
    This forum is for VB.NET, please check the following resources
    http://www.vbforums.com/forumdisplay.php?1-Visual-Basic-6-and-Earlier
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/6a0719fe-14af-47f7-9f51-a8ea2b9c8d6b/where-to-post-your-vb-6-questions?forum=vbgeneral
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • How to split a string around "." expression

    My code is:
    public String removeExtn(String resource){
              String[] splittedName = resource.split(".");
    System.out.println("LENGHT IS: "+ splittedName.length);
              if(splittedName.length >= 3)
                   resource = splittedName[0]+ "." + splittedName[1];
              return resourceName;
         * @param args
         public static void main(String[] args) {
              Test obj = new Test();          
              System.out.println(obj.removeExtn("myfile.xml.sample"));
    But it doesn't split the string around "." and given the arraylength 0. But if I try to use any another character (e.g. "," or ";") it works perfectly fine.
    Please help me.
    Thanks in advance.
    Mansi

    Hi mansi,
    I had a same kind of problem a few days back.
    What I learned was the split() method has a string expression in it, which is usually noted as regex .
    'Regex' is just a short form for 'regular expression'
    You may directly use the string variable you would split around in some cases or may want to use a '\\' before some of the characters.
    I can't place whole information here .So, let me give you that sun site link I read it from.
    This link deals with the whole string class.
    You may want to ctrl+F and split to read on split method.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.htmlThis link talks about the regular expressions
    http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#sumI got his for you from that link :
    \p{Punct} Punctuation: For One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ This is for your knowledge.
    And if you want a quick fix just for your code...
    that'ld be using a
    split(\p{.}) in place where u used a split(.)I have not tried that ...but u may want to!
    Hope that helps.
    Message was edited by:
    Kishorei20
    Message was edited by:
    Kishorei20

  • Replace string with regular expression

    I am new to the regular expression. I am just trying to remove double quotes from a string.
    My sample string is sql statement(SELECT "SCHEMA"."TABLE1"."COLUMN1", "SCHEMA"."TABLE1"."COLUMN2" FROM "SCHEMA"."TABLE1", "SCHEMA"."TABLE2" WHERE "SCHEMA"."TABLE1"."COLUMN1" = "SCHEMA"."TABLE2"."COLUMN1" );
    This is what I came up with.
    String s = query.replaceAll("\\.\"", ".").replaceAll("\"\\.", ".").replaceAll("\\s\"", " ").replaceAll("\\s\"", " ").replaceAll("\",", ",").replaceAll("\"\\s", " ");
    But I want to optimize this line.
    Could anybody tell me how to call replaceAll once with using regular expression instead of calling replaceAll multiple times? Some table or column names can have double quotes, so I want to remove the double quotes without replacing the double quotes which is part of the table or column name.
    I'd appreciated it.

    caesarkim1 wrote:
    I am new to the regular expression. I am just trying to remove double quotes from a string.
    My sample string is sql statement(SELECT "SCHEMA"."TABLE1"."COLUMN1", "SCHEMA"."TABLE1"."COLUMN2" FROM "SCHEMA"."TABLE1", "SCHEMA"."TABLE2" WHERE "SCHEMA"."TABLE1"."COLUMN1" = "SCHEMA"."TABLE2"."COLUMN1" );
    This is what I came up with.
    String s = query.replaceAll("\\.\"", ".").replaceAll("\"\\.", ".").replaceAll("\\s\"", " ").replaceAll("\\s\"", " ").replaceAll("\",", ",").replaceAll("\"\\s", " ");
    ...Note that the following two lines are equivalent:
    s = s.replaceAll("a","").replaceAll("b","");
    s = s.replaceAll("a|b","");

  • How to split a string with a space in between?

    Hi ABAP Guru's,
    Can you please help me out? How can I split a string into two which has a space in between?
    For example: lets suppose the string is 'LA CA USA'. How can I split this string? I have to dynamically determine the number of characters before the space therefore I cannot use number constant such as 2 or 3.
    With best regards,
    Ketan

    Hi
    Try like this
    DATA : opbal TYPE p DECIMALS 2 VALUE 0.
        SELECT * FROM zs_mkpf_mseg
                        into corresponding fields of table it_opbal
                        WHERE werks =  itmat-werks
                        AND matnr = itmat-matnr
                        AND budat = s_budat-low.
      *  sort  it_opbal by budat.
      loop at it_opbal.
    read table it_opbal.
          IF it_opbal-shkzg = 'S'.
            opbal = opbal + it_opbal-menge.
          ELSEIF it_opbal-shkzg = 'H'.
            opbal = opbal + it_opbal-menge * -1.
          ENDIF.
      endloop.
        append opbal TO itab-opbal.
      ENDFORM.                    " opbal_data
    you can also use thi s
    DATA: NAMES(30)    TYPE C VALUE 'Charly, John , Peter',
          NAMES2       TYPE STRING,
          ONE(10)      TYPE C,
          TWO(10)      TYPE C,
          THREE        TYPE STRING,
          FOUR(4)      TYPE C VALUE 'FOUR',
          DELIMITER(2) VALUE ','.
    SPLIT NAMES AT DELIMITER INTO ONE TWO.
    *     ONE contains 'Charly' and TWO contains 'John , Pet'.
    *     SY-SUBRC is 4, because TWO was not large enough to
    *     accommodate the whole of the remaining string
    SPLIT NAMES AT ',' INTO ONE TWO THREE.
    *     ONE contains 'Charly', TWO contains ' John',
    *     THREE contains ' Peter'.
    SPLIT NAMES AT ', ' INTO ONE THREE TWO.
    *     ONE contains 'Charly', THREE contains 'John',
    *     TWO contains 'Peter'.
    CONCATENATE NAMES '' INTO NAMES2 SEPARATED BY SPACE.
    SPLIT NAMES2 AT DELIMITER INTO ONE TWO THREE FOUR.
    *     ONE contains 'Charly', TWO contains 'John',
    *     THREE contains 'Peter ', FOUR is empty.
    SPLIT NAMES2 AT DELIMITER INTO ONE FOUR THREE.
    *     ONE contains 'Charly', FOUR contains 'John',
    *     THREE contains 'Peter', SY-SUBRC is 4, since
    *     FOUR was not large enough (spaces are significant
    *     characters!)
    Reward all helpfull answers
    Regards
    Pavan

  • How to split a string with a delimiting regular expression like "\r"

    Hello!I am a fresh in java programming.Please don't deride my question.What I want to realize is to get the current caret lines and cols in a JTextPane. My question is :After I fetch the string content of the JTextPane and try to split it with the end-line token like "\r" or "\r\n",it always comes me an wrong position.
    here is my code:
    public void caretUpdate(CaretEvent e) {
    int ln,col;
    JTextPane textSource = (JTextPane)e.getSource();
    String sourceString = textSource.getText();
    String subString = sourceString.substring(0,
         (e.getDot() == 0) ? 0 : e.getDot()-1);
    String[] splitString = subString.split("\r",-1);
    ln = splitString.length;
    col = e.getDot() - subString.lastIndexOf("\r");
    setCaretPosition(ln,col); //display ln and col in a label
    I have got puzzled>_<.Please help me.Any help would be appreciated . (^-^)

    Swing text components always use "\n" to separate lines, not "\r" or "\r\n". When you read text in from a file or paste from the clipboard, the line separators are converted to "\n" if necessary. They save the info about what line separators were used in the source file, so if you write the text back to a file it converts them back.

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

  • How To Split the String for "."

    Hi Friends
    I am Using Following Code to Split one String.
    String str = "Jeetendra.choudhary";
    String[] sp_str = str.split(".");
    wdComponentApi.getMessageManager.reportSuccess(str[0]);
    wdComponentApi.getMessageManager.reportSuccess(str[1]);
    but its throwing null pointer exception. 
    when i am using following code its working fine.
    String str = "Jeetendra/choudhary";
    String[] sp_str = str.split("/");
    wdComponentApi.getMessageManager.reportSuccess(str[0]);
    wdComponentApi.getMessageManager.reportSuccess(str[1]);
    what may be the issue and how to split the string with "." ?
    Thanks & Regards
    Jeetendra

    "." is a special character.
    Use
    str.split("\\.");
    Regards
    Benjamin
    Edited by: Benjamin Hansen on Dec 29, 2009 7:52 AM

  • Get the string between li tags, with regular expression

    I have a unordered list, and I want to store all the strings between the li tags (<li>.?</li>)in an array:
    <ul>
    <li>This is String One</li>
    <li>This is String Two</li>
    <li>This is String Three</li>
    </ul>
    This is what have so far:
    <li>(.*?)</li>
    but it is not correct, I only want the string without the li tags.
    Thanks.

    No one?
    Anoyone here experienced with Regular Expression?

  • How to search with regular expression

    I make pdx files so that I can search text quickly. But Acrobat doesn't provide a way to search with regular expression. I'm wondering if there is a way that I don't know to search for regular expression in Acrobat Pro 9?

    First, Acrobat must "mount" the PDX.
    As "Find" does not use the cataloged index, use Shift+Ctrl+F to open the advanced search dialog.
    It may be helpful to first enter Acrobat Preferences and for the Search category tick "Always use advanced search options".
    Back to the Search dialog - use the drop down menu for "Look In" to pick "Select Index" then, if no PDXs show, click the Add button.
    In the Open Index File dialog, browse to the location of the desired PDX and select it.
    OK out and use "Return results containing" to pick a "Match ..." requirement or Boolean.
    To become familiar with query syntax, for Acrobat, it is good to review Acrobat Help.
    http://help.adobe.com/en_US/Acrobat/9.0/Professional/WS58a04a822e3e50102bd615109794195ff-7 c4b.w.html
    Be well...

  • Extract values with Regular Expression

    How to extract values into [ ] using regular expression.
    With data As
    Select 'AAAAAA[10] AAA: 19C' Txt From Dual Union all
    Select 'XX[450]-10A' Txt From Dual Union all
    Select '[5]AVC19C' Txt From Dual Union all
    Select 'FVD[120]D2AC' Txt From Dual
    )I hope this return
    10
    450
    5
    120Thanks in advanced

    user11118871 wrote:
    Thanks for all.
    Hi BluShadow, can you explain what this is doing!?
    ThanksSure.
    Search for ----------------|           /------- Replace the found pattern in the search string with backreference 1
                         /------------\   /\       (the first thing backreferenced in the search string)
    regexp_replace(txt, '^.*\[(.*)\].*$','\1')
                         |\/\/\--/\/\/|
                         | \ \  /  \ \|
                         | | |  |  | |\- End of string
                         | | |  |  | |
                         | | |  |  | \- Any number of characters
                         | | |  |  |
                         | | |  |  \- Right square bracket (escaped)
                         | | |  |
                         | | |  \- any characters (backreferenced by round brackets)
                         | | |
                         | | \- Left square bracket (escaped)
                         | |
                         | \- Any number of characters
                         |
                         \- Start of stringEdited by: BluShadow on Jun 29, 2009 2:19 PM

  • How to split this string(char1)char2(char3)char4 into (char1)char2 , .. etc

    how to split this string (char1)char2(char3)char4 into (char1)char2 , (char3)char4?
    String[] result = "(char1)char2(char3)char4".split("\\(");I want :
    result[0] = "(char1)char2" and
    result[0] = "(char3)char4"
    acutally char1,char2,char3, char4 ... is in the form of the below.
    (any charactors except round brace)any charactors except round brace(any charactors except round brace)any charactors except round brace
    I prefer String.split and Pattern.compile().split.
    Edited by: iamjhkang on Feb 5, 2009 3:37 PM
    Edited by: iamjhkang on Feb 5, 2009 3:41 PM

    iamjhkang wrote:
    especially on
    ?= and ?<
    Thanks.The following:
    (?=...)   // positive look ahead
    (?!...)   // negative look ahead
    (?<=...)  // positive look behind
    (?<!...)  // negative look behindare all "look-arounds". See: [http://www.regular-expressions.info/lookaround.html]

  • Grouping & Back-references with regular expressions on Replace Text window

    I really appreciate the inclusion of the Regular Expressions in the search & replace feature. One thing I am missing is back-references in the replacement expression. For instance, in the unix tools vi or sed, I might do something like this:
    s/\(firstPart\) \(secondPart\) \(oldThirdPart\)/\2 \1 newThirdPart/g
    which would allow me to switch the places of firstPart and secondPart, and totally replace thirdPart. If grouping and back-references are already present in the Replace Text window, how does one correctly invoke them?

    duplicate of Grouping & Back-references with regular expressions on Replace Text window

  • How to split the string by datetime in sql

    Hi,
    How to split the string by datetime in sql, I've a table with comments column stores comments by datetime, while selecting I want to split and show as in rows by each jobref.
    can anyone help me in this please.
    Thanks,

    declare @callcentre table (comments varchar(max),lbiref varchar(200))
    insert into @callcentre
    select '(28/10/2014 14:56:14) xyz ..... call  logged   (28/10/2014 14:56:58) xyz ..... call updated   (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
    insert into @callcentre
    select '(29/10/2014 14:56:14) xyz ..... call  logged   (29/10/2014 14:56:58) xyz ..... call updated   (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
    insert into @callcentre
    select '(30/10/2014 14:56:14) xyz ..... call  logged   (30/10/2014 14:56:58) xyz ..... call updated  
    output:
    1) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call  logged ,'Vi2910201'
     2) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910201'
    3) 28/10/2014 14:57:41,  (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910201'
    4) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call  logged ,'Vi2910202'
     5) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910202'
    6) 28/10/2014 14:57:41,  (28/10/2014 14:57:41)xyz ..... call updated,'Vi2910202'
    7) 28/10/2014 14:56:14, (28/10/2014 14:56:14) xyz ..... call  logged ,'Vi2910203'
     8) 28/10/2014 14:56:58 ,(28/10/2014 14:56:58) xyz ..... call updated ,'Vi2910203'
    Thanks,
    See this illustration
    declare @callcentre table (comments varchar(max),lbiref varchar(200))
    insert into @callcentre
    select '(28/10/2014 14:56:14) xyz ..... call logged (28/10/2014 14:56:58) xyz ..... call updated (28/10/2014 14:57:41)xyz ..... call updated','Vi2910201'
    insert into @callcentre
    select '(29/10/2014 14:56:14) xyz ..... call logged (29/10/2014 14:56:58) xyz ..... call updated (29/10/2014 14:57:41)xyz ..... call updated','Vi2910202'
    insert into @callcentre
    select '(30/10/2014 14:56:14) xyz ..... call logged (30/10/2014 14:56:58) xyz ..... call updated','Vi2910203'
    SELECT LEFT(p.u.value('.[1]','varchar(max)'),CHARINDEX(')',p.u.value('.[1]','varchar(max)'))-1) AS [Date],
    '(' + p.u.value('.[1]','varchar(max)') AS comments,
    lbiref
    FROM
    SELECT lbiref,CAST('<Root>' + STUFF(REPLACE(comments,'(','</Data><Data>'),1,7,'') + '</Data></Root>' AS XML) AS x
    FROM @callcentre c
    )t
    CROSS APPLY x.nodes('/Root/Data')p(u)
    and the output
    Date comments lbiref
    28/10/2014 14:56:14 (28/10/2014 14:56:14) xyz ..... call logged Vi2910201
    28/10/2014 14:56:58 (28/10/2014 14:56:58) xyz ..... call updated Vi2910201
    28/10/2014 14:57:41 (28/10/2014 14:57:41)xyz ..... call updated Vi2910201
    29/10/2014 14:56:14 (29/10/2014 14:56:14) xyz ..... call logged Vi2910202
    29/10/2014 14:56:58 (29/10/2014 14:56:58) xyz ..... call updated Vi2910202
    29/10/2014 14:57:41 (29/10/2014 14:57:41)xyz ..... call updated Vi2910202
    30/10/2014 14:56:14 (30/10/2014 14:56:14) xyz ..... call logged Vi2910203
    30/10/2014 14:56:58 (30/10/2014 14:56:58) xyz ..... call updated Vi2910203
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Dumbfounded by Scanner processing String using regular expression

    I was reading Bruce Eckel's book when I came across something interesting: extending Scanner with regular expressions. Unfortunately, I was confronted with an issue that doesn't make much sense to me: if the String that I am scanning contains a hyphen, the Scanner doesn't produce anything. As soon as I take it out, it all works like a charm. Here is my example:
    import java.util.Scanner;
    import java.util.regex.*;
    public class StringScan {
    public static void main (String [] args){
         String input = "there's one caveat when scanning with regular expressions";
         Scanner scanner = new Scanner (input);
         String pattern = "[a-z]\\w+";
         while (scanner.hasNext(pattern)){
              scanner.next(pattern);
              MatchResult match = scanner.match();
              String output = match.group();
              System.out.println(output);
    }What could be the reason? I imagined it could be because the hyphen for some reason gets given a special meaning but when I tried escaping it, it still didn't work.

    Thanks for your prompt reply.
    I have figured out what was wrong with my code, by the way. Since a single quote is not a word character, it does not match w+. And as the very first input token does not match, the scanner stops immediately. I rewrote my regex to "[a-z].*" and now it does work.

Maybe you are looking for

  • Outlook 2007 intermitent loss of connection at remote VPN Site

    We have some remote sites connected by IPSEC site-to-site VPN. Users run Outlook 2007 connected to Exchange 2007 at the main site. It is common for Outlook to go through periods of  losing and regaining connections: Outlook displays constantly connec

  • Organization address: condense into 2 lines

    Hi , I am using organizational address.. i am using following conditions output starts with paragraph : * No of lines to be used            : 2 use PO. BOX i want to print the a ddress in 2 lines instead in 3.. but when i tried printing in 2 lines...

  • VirtualBox: KDE Compiz does not work

    Hi, I have installed Arch in VirtualBox and installed the GuestAdditions sucessfully (everything works: Mouse, Colour Deep, etc.) But I cant enable the Compiz effects and also the taskbar isnt transparent. Of course Ive enabled 3D in the Menu with 12

  • Just trying to post in iPhoto discussion group. . .

    I'm trying to post a question in the iPhoto discussion group, but there is no "post new topic" option. Any ideas on how to get there??? Thanks, KM.

  • Problem with infotype0000

    Hello everyone, I am having a problem while uploading files through bdc for infotype 0000 .When I upload the bdc data I don't get an error message but when I check it in PA30 I could see that there is a problem showing "No data stored for actions in