Java regex split

i have a file containing names followed by city and emailids,
such as,
name1 city1 email1 email2
name2 city2 email1 email2
in perl, i can write a code,
such as,
($name,$city,$email)=split /\s+/,$line,3;
Here $line is each line from the input file.
to store three parts separately in 3 strings.
How can i do that in java using regex and split?
I need $name to contain name1,name2 etc.
and $city to contain city1,city2 etc...
Anyone familiar with this please help...
- Mani

public class SplitString
     private String testStr = "Hi There";
     public SplitString()
          String[] results = testStr.split(" ");
          System.out.println(results[0] + ":" + results[1]);
      * @param args
     public static void main(String[] args)
          new SplitString();
[/code/
i have a file containing names followed by city and
emailids,
such as,
name1 city1 email1 email2
name2 city2 email1 email2
in perl, i can write a code,
such as,
($name,$city,$email)=split /\s+/,$line,3;
Here $line is each line from the input file.
to store three parts separately in 3 strings.
How can i do that in java using regex and split?
I need $name to contain name1,name2 etc.
and $city to contain city1,city2 etc...
Anyone familiar with this please help...
- Mani

Similar Messages

  • Java Regex Pattern

    Hello,
    I have parsed a text file and want to use a java regex pattern to get the status like "warning" and "ok" ("ok" should follow the "warning" then need to parser it ), does anyone have idea? How to find ok that follows the warning status? thanks in advance!
    text example
    121; test test; test0; ok; test test
    121; test test; test0; ok; test test
    123; test test; test1; warning; test test
    124; test test; test1; ok; test test
    125; test test; test2; warning; test test
    126; test test; test3; warning; test test
    127; test test; test4; warning; test test
    128; test test; test2; ok; test test
    129; test test; test3; ok; test testjava code:
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

    sorry, I try to expain it in more details. I want to parse this text file and save the status like "warning" and "ok" into a list. The question is I only need the "ok" that follow the "warning", that means if "test1 warning" then looking for "test1 ok".
    121; content; test0; ok; 12444      <-- that i don't want to have
    123; content; test1; warning; 126767
    124; content; test1; ok; 1265        <-- that i need to have
    121; content; test9; ok; 12444      <-- that i don't want to have
    125; content; test2; warning; 2376
    126; content; test3; warning; 78787
    128; content; test2; ok; 877666    <-- that i need to have
    129; content; test3; ok; 877666    <-- that i need to have
    // here maybe a regex pattern could be deal with my problem
    // if "warning|ok" then list all element with the status "warning and ok"
    String flag= "warning";
              while ((line= bs.readLine()) != null) {
                   String[] tokens = line.split(";");
                   for(int i=1; i<tokens.length; i++){
                        Pattern pattern = Pattern.compile(flag);
                        Matcher matcher = pattern.matcher(tokens);
                        if(matcher.matches()){
    // save into a list

  • Java Regex Pipe Delimited ?

    Hello
    I am trying to split the string which is pipe delimited. I am new to Regex and new to Java.
    My Java/Regex code line to split is:
    listColumns = aLine.split("\\|"); // my code has 2 backslash-escapes chars plus 1 pipe char but this forum does not allow me to put pipes or escapes correctly and plain text help is of NO HELP 8^(
    My input string has 3 leading and 4 trailing pipe characters
    My Output from split: (3 leading emptry strings work but 4 trailing pipe delimiters dont work)
    SplitStrings2:[]
    SplitStrings2:[]
    SplitStrings2:[]
    SplitStrings2:[col1]
    SplitStrings2:[col3]
    SplitStrings2:[col4]
    I do get 3 empty strings for all 3 leading pipes but no empty strings for the any traling 4 pipe characters.
    What do I need to change the code such that all repeated pipes resulted in same number of empty strings returned by split method?
    thanks
    YuriB
    Edited by: yurib on Nov 28, 2012 12:25 PM
    Edited by: yurib on Nov 28, 2012 12:25 PM
    Edited by: yurib on Nov 28, 2012 12:29 PM

    1. The pipe is a meta-character so escape it.
    2. Split rolls things up for you unless you tell it otherwise.
    String s = "|||A|B|C||||";
    String[] array = s.split("[|]", 10);
    for(int i=0; i < array.length; i++)
         System.out.println("" + i + ": " + array);

  • Test Activities in BW after ABAP /JAVA Stack Split

    Hi All,
    We have recently EHP upgrade in our system .Now to improve performance we have done ABAP/JAVA stack split .
    1.Can you please suggest what are the test activities should be done from BW side after upgrade ?
    2.Can you explain what issue we might face ?
    Please provide list of checks need to be performed specific to this split .
    Thanks in advance .
    Regards,
    Jaya Tiwari

    jaya tiwari wrote:
    Hi All,
    >
    > We have recently EHP upgrade in our system .Now to improve performance we have done ABAP/JAVA stack split .
    > 1.Can you please suggest what are the test activities should be done from BW side after upgrade ?
    > 2.Can you explain what issue we might face ?
    > Please provide list of checks need to be performed specific to this split .
    >
    > Thanks in advance .
    >
    > Regards,
    > Jaya Tiwari
    There are no standard issues in this split. Only thing you need to do is integration testing for scenario like SSO, Bex Reports etc.
    Thanks
    Sunny

  • Converting sed regex to Java regex

    I am new to reguler expressions.I have to write a regex which will do some replacements
    If the input string is something like test:[email protected];value=abcd
    when I apply the regex on it,this string should be changed to test:[email protected];value=replacedABC
    I am trying to replace test.com and abcd with the values i have supplied...
    The regex I have come up with is in sed
    s/\(^.*@\)\(.*\)$/\1replaceTest.com;value=replacedABC/i
    Now I am trying to get the regex in Java,I would think it will be something like (^.*@\)(.*\)$\1replaceTest.com;value=replacedABC
    But not sure How i can test this.Any idea on how to make sure my java regex is valid and does the required replacements?

    rsv-us wrote:
    Yep.Agreed.
    Since that these replacements should be done in a single regex.Note that the sed replacement I posted is really made of two replacements! Just like your Java solution would.
    I think once we send this regex to the third party,they will haev to use either sed or perl(will perl do this replacements,not sure though) to get the output.
    Since we are not sure what tool/software the third party is going to use,I was trying to see how i can really test this.Then I read about sed and this regex as is didn't work,so,I had to put all the sed required / and then the regex had become like s/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/iAgain: AFAIK that does not work. I tried it like this:
    {code}$ echo test:[email protected];value=abcd | sed 's/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/i'and the following is returned:test:[email protected] that we will have to send the java regex to the third party,I was trying to see how i can convert this sed regex to java.If I am right,with jave regex,we won;t be able to all the finds and replacements in a single regex..right?...If this is true,this will leave me a question of whether I need to send the sed regex to the thrid party or If I send java regex,they have to convert that to either sed or perl regex.
    One more question,can we do thse replacement in perrl also,if so,what will the equivalent regex for this in perl?
    I can't understand what you are talking about. The large amount of spelling errors also doesn't help to make it clearer.
    Good luck though.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • What is the escape character for DOT in java regex?

    How to specify a dot character in a java regex?
    . itself represents any character
    \. is an illegal escape character

    The regex engine needs to see \. but if you're putting it into a String literal in a .java file, you need to make it \\., as Rene said. This is because the compiler also uses \ as an escape character, so it will take the first \ as escaping the second one, and remove it, and the string that gets passed onto the regex will be \.

  • Java Regex groups with quantifiers.

    I'm a bit stuck on a regex , i want to do something similar to this :
    (dog){6}
    dogdogdogdogdogdog
    and returned I want 6 seperate groups with 'dog' in each one.
    This works fine with jakarta-regexp but when I use the {} quantifiers in Java regex I lose the groupings which i'm looking for and just get a single group with a value of 'dog'
    I'm sure i'm doing something something stupid here and help would be great!

    You can't do this with the SunJDK regex engine without using find() with a Matcher.
    I consider this feature of jakarta-regex to be a bug and reported it (and a couple of other features) as such several years ago. The feature makes it incompatible with most regex engines I have used.

  • JAVA Regex Illegal Characters

    Hello - I am trying to find a list of all illegal characters which have to be escaped in JAVA Regex pattern matching but I cannot find a complete list.
    Also I understand that when doing the replaceall function that there is a special list of characters which can't be used for that as well, which also have to be escaped differently.
    If anyone has access to a full complete list as to when to escape and how I would greatly appreciated it!
    Thanks,
    Dan

    I also noticed this below link:
    http://java.sun.com/docs/books/tutorial/extra/regex/literals.html
    It said the following characters are meta-characters in regex API:
    ( [ { \ ^ $ | ) ? * + .
    But it also says the below:
    Note: In certain situations the special characters listed above will not be treated as metacharacters. You'll encounter this as you learn more about how regular expressions are constructed. You can, however, use this list to check whether or not a specific character will ever be considered a metacharacter. For example, the characters ! @ and # never carry a special meaning.
    Does anyone know if there would be any issues if I escaped when a character didn't need to be escaped?

  • Java regex problem

    Hi:
    I have the following texts in a flat file:
    scheduler is running
    system default destination: llp
    device for ps3: /dev/ps3
    device for ps: /dev/ecpp0
    device for llp: /dev/ecpp0
    How can I use java regex to print out the string after "device for " in this case the string "ps3" ,"ps" and "llp".

        static final Pattern DEVICE_PATTERN = Pattern.compile(
                                          "device for ([^:]++)" );
        String text = "";
        Matcher m = DEVICE_PATTERN.matcher( text );
        while ( (text = bufferedReader.readLine()) != null ) {
            if ( m.reset(text).lookingAt() ) {
                String device = m.group( 1 );
        }

  • Sed rules to java regex

    Hi,
    what is the connection between sed regex rules and java regex rule. Is there an easy way to convert sed to java? or do i have to learn sed?....
    Thanks

    IIRC, Java regex rules are like Perl's (although the syntax for invocation differs a bit), and Perl's are basically a superset of sed's, except there's a difference with parentheses. In Perl/Java, parentheses always group and you have to backslash-quote them to make them interpreted as plain parenthesis characters, whereas in sed, you backslash-quote them to make them be interpreted as grouping indicators.
    Why? What problem are you having?

  • Java Regex, how do I replace \\ with \\\\?

    Hello,
    The following line doesn't work: someString.replaceAll("\\", "\\\\");
    The error I get is the following:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
    ^
         at java.util.regex.Pattern.error(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.util.regex.Pattern.<init>(Unknown Source)
         at java.util.regex.Pattern.compile(Unknown Source)
         at java.lang.String.replaceAll(Unknown Source)
         at TSPEngine.main(TSPEngine.java:34)
    How do I fix this?
    Thanks in advance,

    Interference wrote:
    Hello,
    The following line doesn't work: someString.replaceAll("\\", "\\\\");
    The error I get is the following:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1"\\" is how you represent "\" in a String literal in Java, since "\" is an escape character. But "\" is also an escape character in regular expressions, meaning to represent a literal "\" in a Java regex you need "\\\\". Your second string should be fine since it's not interpreted as a regular expression to my knowledge.
    Edit:
    No, the second string DOES need to be "\\\\\\\\".
    Edited by: endasil on 17-May-2010 11:46 AM

  • How do you get java regex to match two different pattern

    Hi,
    I am having trouble getting getting java regex to match two pattern: "unknown host" or "100%".
    Here is a snippet of my code:
    try{
    Process child = Runtime.getRuntime().exec(" perl c:\\ping.pl");
    BufferedReader in = new BufferedReader( new InputStreamReader( child.getInputStream() ));
    String patternStr = "(unknown host | 100 %)";
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(" ");
    String line = null;
    while ( (line = in.readLine()) != null){
    System.out.println(line);
    matcher.reset(line);
    if (matcher.find())
    // line matches throws pattern
    System.out.println("match string");
    else
    System.out.println("no matches");
    I thought the "|" means OR but somehow it is not working.
    kirk123

    Hi,
    with String patternStr = "(unknown host | 100 %)"; you are looking
    for the strings "unknown host " OR " 100 %", with the spaces after host and before 100.
    Try "(unknown host|100 %)"
    hope, this will help you

  • Simple Java regex question

    I have a file with set of Name:Value pairs
    e.g
    Action1:fail
    Action2:pass
    Action3:fred
    Using regex package I Want to get value of Name "Action1"
    I have tried diff things but I cannot figure out how I can do it. I can find Action1: is present or not but dont know how I can get value associated with it.
    I have tried:
    Pattern pattern = Pattern.compile("Action1");
    CharSequence charSequence = CharSequenceFromFile(fileName); // method retuning charsq from a file
    Matcher matcher = pattern.matcher(charSequence);
    if(matcher.find()){
         int start = matcher.end(0);
         System.out.println("matcher.group(0)"+ matcher.group(0));
    how I can get value associated with specific tag?
    thanks
    anmol

    read the data from the text file on a line basis and you can do:
    String line //get this somehow
    String[] keyPair = line.split(":")g
    System.out.println(keyPair[0]); //your name
    System.out.println(keyPair[1]); //your valueor if you've got the text file in one big string:
    String pattern = "(\\a*):(\\a*)$"; //{alpha}:{alpha}newline //?
    //then
    //do some things with match objects
    //look in the API at java.util.regex

  • Java File Splitting

    Hi,
    We're working on a distributed file processing project. My friend told me we can split files using a command in Java. I searched for it but found no such command. It's not like splitting a text file according to the number of characters, but splitting any kind of file into smaller pieces. Is there a command for that in Java or will we have to write a whole program for it?

    NikhilKini wrote:
    Hi,
    We're working on a distributed file processing project. My friend told me we can split files using a command in Java. I searched for it but found no such command. It's not like splitting a text file according to the number of characters, but splitting any kind of file into smaller pieces. Is there a command for that in Java or will we have to write a whole program for it?No, there's no such method in the standard Java classes. You will have to write your own, or have a look at Apache's IO library: chances are they have something like it.
    [http://commons.apache.org/io/]
    Good luck!

  • Non greedy Java Regex not working

    I am trying to parse some HTML and using regex for it.
    Here is the HTML I want to parse:
    <a href="google.com">Lololo</a> <a href="tttt.com">Read More</a>I want to find the second anchor tag with "Read More" text only.
    The Regex I am using to parse the String is:
    <a.*?>\s*Read More.*?</a>But I am still getting the entire string back after the regex match instead of only the second A tag with Read More text.
    Can anyone help explain what is wrong in my regex?
    I am using Java 6 with Eclipse IDE 3.4.

    danbrown wrote:
    import java.util.regex.*;
    class TestRegEx {
    public static void main(String[] args) {
    String regex = "<a.*?>\\s*Read More.*?</a>";
    String toChk = "asfafadsfasfadsf <a href="google.com">Lololo</a> d ds <a href="tttt.com">Read More</a> zzzzzz";
    String cleanStr = Pattern.compile(regex,Pattern.CASE_INSENSITIVE).matcher(cleanStr).replaceAll("")
    //Expected output should be "asfafadsfasfadsf <a href="google.com">Lololo</a> d ds zzzzzz"
    //Only the '<a href="tttt.com">Read More</a>' must be deleted no other part of the String must be deleted.
    System.out.println(cleanStr);
    You've stated what the expected output is, but left off what the actual output is. Although in all fairness, there can't be any actual output, since that code will not compile.

Maybe you are looking for

  • Photoshop CC doesn't recognize the right mouse button of my Wacom Intuos pen tablet, how do I solve this?

    For some reason photoshop CC doesn't respond to the right mouse button that is on my tablet pen. It's strange because it does work for illustrator CC, so why would photoshop CC not respond to it? Anyhow, help please! I have a wacom intuos pen tablet.

  • Issue with KeyEvent for Command Prompt

    Using below code, when Event keys like "F7" are executed on the application to test while running from openscript it works fine. Whereas if the same script is executed using command line as below, then "F7" is executed for command prompt itself inste

  • Dump error with GUI 7.1

    Hello, I have GUI 7.1 with patch 6 on my PC. I receive a dump error 'EXCEPTION_ERROR' when I double click on a BI transfer link and can not run the program. On another PC with a lower patch level everything runs fine. I don't think it is caused by a

  • Out of memory Problem

    Hello everyone ! I've developped a Brain Training application for Japan with the french version of Director MX 2004. To display Japanese texts, I have used embedded Flash movies which contains a Japanese font. This program is on the market for a few

  • Error message with profile

    for the past 3 days I have spent 8 hours on the Firefox support page my problem is after restarting my computer for about 30 to 60 minutes Firefox will stop loading pages and then I have to close Firefox to restart it and a message pops up saying Fir