Using a regular expression in String's split method

I have a String that is delimited by commas that I would like to split into a String array. However, the problem is that it is valid that some of the elements could have embeded commas in them. These "extra" commas are always in a predefined pattern though.
For example, the String that I want to parse may look like this (quotes omitted):
data with spaces and tabs , more data with more spaces, now for the problem(5,9), and now some more text and spaces
What I would like the result to be (shown below as if each element has been trimmed):
data with spaces and tabs
more data with more spaces
now for the problem(5,9)
and now some more text and spaces
string.split("[,&&[^[\\(.,.\\)]]]");The idea being that I want to split on all commas except those that are in the pattern (5,9). Where 5 and 9 could be any integer.
The above expression isn't working. It isn't ignoring the comma in the pattern.
Any suggestions?
Thanks.

i dunno if this help...
There is a class called the StringTokenizer class where it splits the String and delimiter up..e.g
String s1="Hello,Welcome,Can";
String[ ] arr=new String[3];
To use the StringTokenizer, you create.
StringTokenizer st=new StringTokenizer(s1,",");
//this will split the words, hello,welcome and can into "Tokens"
Then use this method .hasMoreTokens( )
int i=0
while(st.hasMoreTokens( ) ==true) {
arr=st.nextToken( );
i++;
Hope this helps! =)

Similar Messages

  • Wat should be the regular expression for string MT940_UB_*.txt to be used in SFTP sender channel in PI 7.31 ??

    Hi All,
    What should be the regular expression for string MT940_UB_*.txt and MT940_MB_*.txt to be used as filename inSFTP sender channel in PI 7.31 ??
    If any one has any idea on this please let me know.
    Thanks
    Neha

    Hi All,
    None of the file names suggested is working.
    I have tried using - MT940_MB_*\.txt , MT940_MB_*.*txt , MT940*.txt
    None of them is able to pick this filename - MT940_MB_20142204060823_1.txt
    Currently I am using generic regular expression which picks all .txt files. - ([^\s]+(\.(txt))$)
    Let me know ur suggestion on this.
    Thanks
    Neha Verma

  • Regular Expressions and String

    How do I return a String array as follow using regular expression.
    String[] strArray = {"Now is the time", "you can optionally preview your post","message by using a number of special tokens."}
    from this string
    <separator>Now is the time</separator><separator>you can optionally preview your post</separator><separator>message by using a number of special tokens.</separator>
    Note: The string has the <separator> XML tag

    How do I return a String array as follow using regular
    expression.
    String[] strArray = {"Now is the time", "you can
    optionally preview your post","message by using a
    number of special tokens."}
    from this string
    <separator>Now is the time</separator><separator>you
    can optionally preview your
    post</separator><separator>message by using a number
    of special tokens.</separator>
    Note: The string has the <separator> XML tag
    This cannot be done using simple regular expressions - at least not if your number of <separator>s is random, which is what you seem to imply.
    Simple regular expressions are one-off, that means it can have a String array as a result, but only to the amount of brackets in the regex.
    a regex like:
    <separator>([^<]*)</separator><separator>([^<]*)</separator><separator>([^<]*)</separator>
    would return what you want, but I doubt that it is as flexible as you want it to be.

  • Use a regular expression to do this...

    I need to process this line : "STRTsomeEND.STRTsome2END.STRTsome3END"
    to get an array with this values :
    String[] processedLine = {
    {"STRTsomeEND."}
    {"STRTsome2END."}
    {"STRTsome3END."}
    I tried to use this regular expression to do the work: (STRT[.*]END.)+ but doesn't work. Also I tried with this expresion STRT[.*]END. But I only got the first ocurrence ("STRTsomeEND") .
    Can anybody help me?

    zkropotkine wrote:
    1) "." is a regex flag.I saw in the table and it said that the "." symbol doesn't need the escape: )
    when you ask a question and then someone gives you advice you should
    give them the benefit of the doubt (for at least a little while).
    did you take a moment to try to understand what i was saying about escaping the "."?
    anyway, your regex should be:
    (START)(.*?)(END)\ \ .
    the "?" after the "\*" means "reluctant". you dont want the ".\*" to grab up everything.
    with the reluctant modifier "?" the regex should stop and grab the first available "END".
    and finally, if you meant the "." at the end of "STARTsomethingEND." literally then:
    you need to escape the "."

  • Track the entered answer using the Regular expression

    Hi,
    I am building a Q&A application which does have user to answer descriptive answer for the question(Text based answer rather than objective)
    in this case how we can track the entered answer by the user is the correct one? how we can capture the entered answer and then check with the correct
    answer in the DB? Yes we need to use a regular expression , but how we know that entered one is matching with the one in the DB
    as the user can answer in lengthy or short form ? Hence please clarify how we can proceed?
    Thanks.

    797836 wrote:
    Hi,
    I am building a Q&A application which does have user to answer descriptive answer for the question(Text based answer rather than objective)
    in this case how we can track the entered answer by the user is the correct one? how we can capture the entered answer and then check with the correct
    answer in the DB? Yes we need to use a regular expression , but how we know that entered one is matching with the one in the DB
    as the user can answer in lengthy or short form ? Hence please clarify how we can proceed?
    I don't see how regular expressions help at all with this problem ! What made you think they can help?

  • Regular Expression on String

    Hi Experts,
    I am working on jdev 11.1.1.6.0
    I have to validate input text, which user can able to enter alpha number with separated by ','.  for example TP103,TP104,TP105........ or 1023,1034,1034....... But they shouldn't enter single ',' or ,,,,,,,,,,,,,,,  . Can any one tell me how to write regular expression for this.
    Thanks.

    user can able to enter alpha number with separated by ','.
    But they shouldn't enter single ',' or ,,,,,,,,,,,,,,,
    Is a ',' required to be validated using a regular expression?
    Refer
    Lesson: Regular Expressions (The Java&amp;trade; Tutorials &amp;gt; Essential Classes)

  • Regular expressions and string matching

    Hi everyone,
    Here is my problem, I have a partially decrypted piece string which would appear something like.
    Partially deycrpted:     the?anage??esideshe?e
    Plain text:          themanagerresideshere
    So you can see that there are a few letter missing from the decryped text. What I am trying to do it insert spaces into the string so that I get:
                        The ?anage? ?esides he?e
    I have a method which splits up the string in substrings of varying lengths and then compares the substring with a word from a dictionary (implemented as an arraylist) and then inserts a space.
    The problem is that my function does not find the words in the dictionary because my string is only partially decryped.
         Eg:     ?anage? is not stored in the dictionary, but the word �manager� is.
    So my question is, is there a way to build a regular expression which would match the partially decrypted text with a word from a dictionary (ie - ?anage? is recognised and �manager� from the dictionary).

    I wrote the following method in order to test the matching using . in my regular expression.
    public void getWords(int y)
    int x = 0;
    for(y=y; y < buff.length(); y++){
    String strToCompare = buff.substring(x,y); //where buff holds the partially decrypted text
    x++;
    Pattern p = Pattern.compile(strToCompare);
    for(int z = 0; z < dict.size(); z++){
    String str = (String) dict.get(z); //where dict hold all the words in the dictionary
    Matcher m = p.matcher(str);
    if(m.matches()){
    System.out.println(str);
    System.out.println(strToCompare);
    // System.out.println(buff);
    If I run the method where my parameter = 12, I am given the following output.
    aestheticism
    aestheti.is.
    demographics
    de.o.ra.....
    Which suggests that the method is working correctly.
    However, after running for a short time, the method cuts and gives me the error:
    PatternSyntaxException:
    Null(in java.util.regex.Pattern).
    Does anyone know why this would occur?

  • Regular Expressions and String variables

    Hi,
    I am attempting to implement a system for searching text files for regular expression matches (similar to something like TextPad, etc.).
    Looking at the regular expression API, it appears that you can only match using string variables. I just wanted to make sure this is true. Some of these files might be large and I feel uneasy about loading them into ginormous Strings. Is this the only way to do it? Can I make a String as big as I want?
    Thanks,
    -Mike

    Newlines are only a problem if you're reading the
    text line-by-line and applying the regexp to each
    line. It wouldn't catch expressions that span
    lines.
    @sabre150: your note re: CharSequence -- so what
    you're suggesting is to implement a CharSequence that
    wraps the file contents, and then use the regexps on
    the whole thing? I like the idea but it seems like
    it would only be easy to implement if the file uses a
    fixed-width character set. Or am I missing
    something...?You are correct for the most basic implementation. It is very easy to create a char sequence for fixed width character sets using RandomAccessFile. Once you go to character sets such as UTF-8 then more effort is required.
    While ever the regex is moving forward thought the CharSequence one char at a time there is no problem because one can wrap a Reader but once it backtracks then one needs random access and one will need to have a buffer. I have used a ring buffer for this which seems to work OK but of course this will not allow the regex to move to any point in the CharSequence.
    'uncle_alice' is the regex king round here so listen to him.
    :-( I should read further ahead next time!
    Message was edited by:
    sabre150
    Message was edited by:
    sabre150

  • Regular Expression Fails String replaceAll

    I am trying to use regular expressions to replace double backslashes in a string with a single backslash character. I am using version 1.4.2 SDK. Upon invoking the replaceAll method I get a stack trace. Does this look like a bug to anyone?
    String s = "text\\\\";  //this results in a string value of 'text\\'
    String regex = "\\\\{2}";  //this will match 2 backslash characters
    String backslash = "\\";
    s.replaceAll(regex,backslash); java.lang.StringIndexOutOfBoundsException: String index out of range: 1
         at java.lang.String.charAt(String.java:444)
         at java.util.regex.Matcher.appendReplacement(Matcher.java:551)
         at java.util.regex.Matcher.replaceAll(Matcher.java:661)
         at java.lang.String.replaceAll(String.java:1663)
         at com.msdw.fid.fitradelinx.am.client.CommandReader.read(CommandReader.java:55)
         at com.msdw.fid.fitradelinx.am.client.CommandReader.main(CommandReader.java:81)
    Exception in thread "main"

    Skinning the cat -
    public class Fred12
        public static void main(String[] args)
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "[\\\\]{2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(\\\\){2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(?:\\\\){2}";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "(?:\\\\)+";  //this will match 2 or more backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
                String s = "text\\\\";  //this results in a string value of 'text\\'
                String regex = "\\\\\\\\";  //this will match 2 backslash characters
                String backslash = "\\\\";
                System.out.println(s.replaceAll(regex,backslash));
    }

  • Regular Expressions on strings

    How would I go about creating a regular expression in LabVIEW that, say, takes an input of a list of numbers (1, 2, 3, 4, 5) and turns it into an array with the elements [1, 2, 3, 4, 5]? If someone could show me example code, I would be quite grateful.
    Thanks.
    Using LabVIEW 2009 on Windows Vista

    Spreadsheet String to Array should work for conversion to strings or numbers...
    Richard
    Attachments:
    stringarr.gif ‏18 KB

  • Use of Regular Expression...

    Hi ,
    How should i write a reg_exp function returning into 3 variables the parts of the following string...?????
    ("HIS"."EISAG"."DATE_INPUT")
    In other words , i would like in three variables to get the string HIS , EISAG , DATE_INPUT using the Reg_exp function
    Thanks , A lot
    Simon

    Hi sgalaxy,
    Try this.
    -- setup
    create table t ( c varchar2(30) );
    insert into t values ( '("HIS"."EISAG"."DATE_INPUT")' );
    insert into t values ( '("ABC"."DEF"."GHI")' );
    insert into t values ( '("ABC"."DEF")' );
    insert into t values ( '("ABC")' );
    insert into t values ( '("".""."")' );
    insert into t values ( null );
    insert into t values ( 'XYZ' );
    set null '(null)'
    -- v10 solution
    column result_1 format a10
    column result_2 format a10
    column result_3 format a10
    select
      2    c,
      3    regexp_replace
      4      ( regexp_substr( c, '".*?"', 1, 1 ),
      5        '"(.*?)"',
      6        '\1'
      7      ) as result_1,
      8    regexp_replace
      9      ( regexp_substr( c, '".*?"', 1, 2 ),
    10        '"(.*?)"',
    11        '\1'
    12      ) as result_2,
    13    regexp_replace
    14      ( regexp_substr( c, '".*?"', 1, 3 ),
    15        '"(.*?)"',
    16        '\1'
    17      ) as result_3
    18  from t
    19  ;
    C                              RESULT_1   RESULT_2   RESULT_3
    ("HIS"."EISAG"."DATE_INPUT")   HIS        EISAG      DATE_INPUT
    ("ABC"."DEF"."GHI")            ABC        DEF        GHI
    ("ABC"."DEF")                  ABC        DEF        (null)
    ("ABC")                        ABC        (null)     (null)
    ("".""."")                     (null)     (null)     (null)
    (null)                         (null)     (null)     (null)
    XYZ                            (null)     (null)     (null)
    -- cleanup
    drop table t;As I recently told another user, if you are interested in learning more about regular expressions I have a tutorial you might find useful at http://www.sqlsnippets.com/en/topic-10759.html .
    Message was edited to fix typos.

  • IR filter using "matches regular expression"

    Hi,
    I am familiar with Perl regular expressions, but I'm having trouble using the IR filter by regular expression in Apex.
    For instance, I would like to search for dates of format 'MM/DD/YY' - can someone tell me how this would be done? I tried '[0-9](2)/[0-9](2)/[0-9](2)' and many other patterns to no avail.
    Also can you point me to a good thread for regular expressions in Apex?
    Thanks for any help.

    Hi,
    you can play around with oracle regular expressions at
    http://www.yocoya.com/apex/f?p=YOCOYA:REGEXP_HOME:0:
    It's an Apex application, albeit "seasoned", where you can build and test the regex and it will be 100% compatible as it runs natively, so it's not simulated on a different platform.
    Most likely the IR filter will make use of REGEXP_LIKE so you can pick that function from the menu.
    Flavio
    http://oraclequirks.blogspot.com
    http://www.yocoya.com

  • How to implement the String class "split()" method (JDK1.4) in JDK 1.3

    is it possible , with some code, to implement the split() method of the String class......which is added in JDK1.4 ..... in JDK1.3
    would be helpful if anyone could suggest some code for this...

    Here it is
    public static String[] split(String source, char separ){
    answer=new Vector();
    int position=-1, newPosition;
    while ((newPosition=source.indexOf(separ,position+1))>=0){
    answer.add(source.subString(position+1,newPosition));
    position=newPosition;
    } //while
    answer.add(source.subString(position+1,source.length-1);
    return (String[])(answer.toArray());
    } //split

  • Regular Express in String.replaceFirst(..)

    I have the following string...
    "this ? is what ?."
    I am trying to replace the ? with an element. What is a regualr expression that would allow me to replace the just first ? with an item. I tried "?" but it say dangling reference... Ideas? The ?'s will be diffrent so I will use replace first. I could use substring and indexof and concatenate strings but I would perfer not to do so.
    String str = "this ? is what ?.";
    Object  o = "katz";
    str = str.replaceFirst("?", o.toString());TIA
    Doopsterus

    ? is a special character--a quantifier--that means "match zero or one of the preceding element". If you want to use it literally, you need to escape it with a backslash. Since the backslash is special in Java string literals, you have to escape the backslash so that one gets through to the regex Pattern.
    Try this: str = str.replaceFirst("\\?", whatever);

  • An additional question about regular expressions with String.matches

    does the String.matches() method match expressions when some substring of the String matches, or does it have to match the entire String? So, if i have the String "123ABC", and i ask to match "1 or more letters" will it fail because there are non-letters in the String, but then pass if i add "1 or more letters AND 1 or more digits"? so, in the latter every character in the String is accounted for in the search, as opposed to the first. Is that correct, or are there ways to JUST match some substring in the String instead of the whole thing? i WILL make some examples too... but does that make sense?

    It has to match the whole String. Use Matcher.find() to match on just a sub-string()

Maybe you are looking for

  • Hotspot click for only some rows in ALV grid for a particular column ?

    Hi there,         In ALV grid, we can make Hotspot enable for all rows in a specified column by specifying in the fieldcatalog with Hotspot attribute set as true. But I want to enable Hotspot only for certain rows in the particular column. I tried wi

  • Can't boot into Mac Partition

    I started out with a simple error in iTunes whenever I tried to update my genius. The error was the following: "We could not complete your iTunes Store request. An unknown error occured (-9812). There was an error in the iTunes Store. Please try agai

  • IPad4 Camera Not Working after ios 7.1.2 install

    The Camera in my iPad4 stopped working after loading ios 7.1.2. The App comes up with a Black Screen and none of the controls work. I loaded another Camera App, Rebooted, Restored and also upgraded to ios 8. None support steps have resolved my camera

  • Avaibility of FTP option in SQL Developer

    Hello, Can any one please help me regarding the FTP option in SQL Developer.As this is avaibable in TOAD. Also let me the navigation if at all there (step in detail) Thankyou for your help.

  • Query to find the number of main meter and its corresponding sub meter

    Hi Expert, I need to build a query to derieve the main meter & it corresponding sub meter in SAP system Please could you let me the table which i should join