Regex in java

hi guys im rubbish at regex basically i was to put the line:
527787     137625     01/11/2005     00:30:00     4
into 5 string varibles using a regular expressions any ideas? so
string a = 527787
string b = 137625
string c = 01/11/2005
string d= 00:30:00
string e = 4
really appreciate any help on this one
AndyT

String[] splitValue = "527787 137625 01/11/2005 00:30:00 4".split(" +");

Similar Messages

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

  • Using regex in java

    I need to get a name from the text box and store it in a String variable.And i should put a condition that the name that is stored in the stirng variable should not start with non alpha numeric characters or special characters.For this i want to use Regular expressions in java.I got a Regex or pattern for this purpose it is shown below
    Pattern:
    ^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$
    And my code is as follows:
    JTextFeild reportnametext;
    String name=reportnametext.getText();
    //here i need to check whether the first charecter of the name is starting with a special character and if it starts with special charecter i need to popup a dialog box that name should not start with special characters.
    Can u plz show me how to implement it in my code

    If you'd have taken the time to go through the links I provided you would have seen [url http://javaalmanac.com/egs/java.util.regex/Case.html]Setting Case Sensitivity in a Regular Expression.
    Pattern p = Pattern.compile("^[a-z0-9]", Pattern.CASE_INSENSITIVE);Regards

  • Regex for Java comments

    Hi everyone,
    Can anyone be so kind and post the simplest working regex pattern that matches all Java comments (multi-line, not in quoted strings, etc).
    I'm starting to use (Java) REs and have been fighting with various combinations of |s, $s, \\*s, Pattern.MULTILINEs and Pattern.DOTALLs for a while now - extending the simple example shown at http://developer.java.sun.com/developer/technicalArticles/releases/1.4regex , under "File Searching".
    Thanks for your time and help!
    -Nido

    Hi Nido,
    I would also be interested in a simple fix. I looked at this for a while and came up short of an easy solution that would cover all contingencies.
    You can easily match a single line comment since it ends at the line return. I tried the pattern
    //[^\r|\n]*
    which works predictably, but of course it doesn't account for the possibility of being inside a quote. You could of course match the whole line and then begin looking for quotes before the "//" but you would also have to look to see whether the quote closes before the "//" or not. And when matching quote marks you also would have to check whether they were escaped or not, since an escaped quote would itself be inside a quoted string.
    This is far from your simple solutions and implicates using a combination of regular expressions and string tokenizers or plain old "indexOf()" matches so that you could count the number of quotes before the "//" and see whether the quote closes or not and verify that no escaped quote marks are treated as quotes themselves.
    for multi-line comments you also have a challenge. In fact I have a question for you and the rest of the community here. How solid is the support for matching multiple-line patterns at this point? I haven't been able to get it to work reliably for me yet, but that may be my misunderstanding. Regardless, if you just strip the line returns from the string (or whatever you're parsing) it will behave as predictably as a single line.
    One trick I've used before (works with other languages as well) is to replace all the line returns with a token of my choice so that I can parse it reliably (since it's now a single line) and then after parsing I can replace the tokens with the original line returns. This makes multi-line parsing very solid but requires at least two extra lines of code.
    Regardless, my poor brain has a hard time thinking of a solid way to match a multi-line comment. The danger is that regular expressions use "greedy" matching by defualt. That is, they try to match as much content as possible by the definition you provide. If you create a catch-all multi-line comment match such as:
    you run the risk of matching all the content found between two or more multi-line comments. You can use
    /\*[^\*]*\*/
    which will definitely not overrun the end of the comment, but it will not work properly if you have a "*" anywhere inside the content of your comment.
    I wonder if you would be better off using a tokenizer or "indexOf()" type system on the multi-line comments so that you could get away from the greedy pattern matching? The other benefit is that line returns would be handled predictably.
    Just some thoughts. Maybe I'm missing something here. Hope you get the simple answer you're looking for yet.

  • Validate URL with Regex in Java

    Can someone please help me out with regex pattern I need to validate a URL.
    Pattern for it has to be as followed.
    -http://
    -www.
    -address
    -. domain
    valid http://www.yahoo.com
    invalid ss.wwsa.asfvqa

    Something like:
    http://www\..+\..{2,4}
    Might work. That's very simple and doesn't check if the last part is valid (i.e. .com, .net, etc) except for being between 2 and 4 characters. The reason is because although there are a set of very common domain names like .com and .net, there are weird ones out there like .tk.
    This pattern also doesn't take into account the fact that the server might have a subdomain... i.e. http://something.website.com. It could be modified easily enough though.
    Edit: Of course don't forget to escape the backslashes if you're using it in a String...
    Edit #2: This also doesn't necessarily take into account international domains such as .co.uk or .co.jp.
    Edited by: ProjectMoon on Feb 8, 2008 9:30 AM
    Edited by: ProjectMoon on Feb 8, 2008 9:45 AM

  • Java.util.regex  vs jarkata-oro on regular expression

    hi, all
    Both java utility (java.util.regex) and jarkata-oro (org.apache.oro.text.perl) provide supports of Perl5 compatible regular expressions. What are your opinions of which one do you choose?
    I've searched in this forum and others online. I don't see this topic. Maybe I miss something...
    Anyway, your opinions/experences are more than welcome.
    thx
    Tim

    One big difference:
    java.util.regex is JAVA 1.4+ only.
    jarkata-oro is JAVA 1.2+

  • WHERE to find [b]java.util.regex.*[\b] package?

    Does anyone know where to obtain a copy of the java.util.regex.* package (separate package)? This is a new package included in version 1.4.0.

    Does anyone know where to obtain a copy of the
    java.util.regex.* package (separate package)?
    This is a new package included in version 1.4.0.Simple:
    Go to your java sdk directory
    $ jar xvf src.jar
    $ cd java/util/regex
    $ javac ASCII.java
    $ javac Matcher.java
    $ javac Pattern.java
    $ javac PatternSyntaxException.java
    $ cd ../../..
    $ jar cvf regex.jar java/util/regex/*.class
    et voila; how difficult can that be ? There is no native, JVM depending stuff in there, although I did not check for dependencies on other new stuff inside the jdk.
    I'm also unaware if this isn't illegal under the agreement with Sun.

  • Help withRegular Expressions in java!

    Hi All,
    I've written some code using the java.util.regex package to try capture some text from a text file. An example of the code is written below:
    // Regexp that will try match in test file
            //Pattern pattern = Pattern.compile("//s*(//d+)//s*");           // won't match
            Pattern pattern = Pattern.compile(".*");                             // matches
            try {
                BufferedReader input =  new BufferedReader(new FileReader(aFile));
                try
                    String line = null;
                    while (( line = input.readLine()) != null)
                        System.out.println(line);
                        // Use regexp to extract test name from text file
                        Matcher matcher = pattern.matcher(line);
                        System.out.println(matcher.lookingAt() );
                finally
                    input.close();
            catch (IOException ex) {
              ex.printStackTrace();
            }The lines of the text file are of the follwing form:
    Number SomeText MoreText Number
    e.g.
    234   testname    50000 If I try capture certain parts of of a line, like the commented out pattern above trying to capture the number, it doesn't match. But if I use the ".*" to capture the whole line it matches. I can't understand why the first pattern doesn't work! Any help in figuring this out would be greatly appreciated!
    thanks.

    Melanie_Green wrote:
    I often refer back to this trusty resource [regex in Java|http://java.sun.com/docs/books/tutorial/essential/regex/index.html]
    MelI still use the test harness from that tutorial sometimes when I'm trying to formulate a regex.

  • Ternary Operator Question (with regex).

    Hi, I was learning regex in java and wrote a program which tests a string to see if it is an email address.
    import javax.swing.*;
    public class IsEmailAddress
         public static void main(String[] args)
              String address = JOptionPane.showInputDialog("Enter an email address");
              if(address.matches("[a-zA-Z0-9\\.]+@\\w+\\.{1}\\w+"))
                   JOptionPane.showMessageDialog(null, "It is an email address");
              else
                   JOptionPane.showMessageDialog(null, "It is not an email address");
    }The above program works correctly. But then I decided to try and make the program only one line inside the main:
    import javax.swing.*;
    public class IsEmailAddress
         public static void main(String[] args)
              JOptionPane.showInputDialog("Enter an email address").matches("[a-zA-Z0-9\\.]+@\\w+\\.{1}\\w+") ? JOptionPane.showMessageDialog(null, "It is an email address") : JOptionPane.showMessageDialog(null, "It is not an email address");
    }I get the compilation error not a statement, what am I doing wrong? Is this even possible?
    Thanks for any help

    I would never use a piece of code like that as part of a bigger program, I wanted to see if it was possible and maybe to learn something about the ternary operator.
    Keeping in mind what you said about the ternary operator having to return something, I was able to make it work:
    import javax.swing.*;
    public class IsEmailAddress
         public static void main(String[] args)
              int a = JOptionPane.showInputDialog("Enter an email address").matches("[a-zA-Z0-9\\.]+@\\w+\\.{1}\\w+") ? JOptionPane.showOptionDialog(null, "It is an email address","Is it an email Adress?",JOptionPane.CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,null,null) : JOptionPane.showOptionDialog(null, "It is not an email address","Is it an email Adress?",JOptionPane.CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,null,null);
    }I chose showOptionDialog because it returns a static int.
    Thank you for your help!!!

  • Importing java classes to XI

    Hello,
    I have a problem to import java.util.regex.Pattern / java.util.regex.Matcher
    Where I can find the all the java classes in the XI?
    How can I know that all the classes where imported?
    Regards
    Elad

    Elad,
    Like pointed by others, you need not import any Jar file for the pattern and matcher classes under Regex.
    I have a UDF working absolutely fine that uses this class.
    I would suggest that you look into the code and try to analyse what the issue is.
    Also, make sure that you have a semicolon after the import of both these classes and the improt statement should be at the top of the UDF under imports.
    Regards
    Bhavesh

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Java pattern matching - perl like

    I have an XML file and I try to match something like this:
    Pattern p = Pattern.compile("category code=\\S{1,} validFrom=\\S{1,}");
    Matcher m = p.matcher (content);
    while (m.find ()) {
    System.out.println ("Found " + m.group ());
    This code works and extracts groups according to the pattern but I want to extract only the value.
    Exemple:
    the string is: category code=23 validFrom=2011-01-01
    I want to extract only *23* and *2011-01-01*.
    Can I do this without manualy parsing the string?
    Thank you.

    XPath is the best solution for this. If you must have regex, see java.until.regex.

  • Trying to Scan in a List of Names Using a Delimiter from a Text File

    Hello everyone,
    I tried posting this question onto [Codecall Forums|http://forum.codecall.net/java-help/16064-trying-scan-list-names-using-delimiter-text-file.html] for an answer, but nobody really helped to solve this problem, so I'm reposting it here.
    I'm trying to solve this problem on the Euler Project for practice. For the first part of the problem, I am supposed to scan in names in the following format: "name1","name2","name3". To solve this, I wrote the following code:
    import java.io.*;
    import java.util.*;
    public class AlphabeticalSort
         public static void main(String args[]) throws IOException
              //import the file
              Scanner input = new Scanner(new File("names.txt"));
              input.useDelimiter("[\",]");
              System.out.println(input.delimiter());
              //scan it for the length of the array
              int n = 0;
              while (input.hasNext())
                   input.next();
                   n++;
              System.out.println(n);
              //import the names into the array
              Scanner input2 = new Scanner(new File("names.txt"));
              input2.useDelimiter("[\",]");
              String[] names = new String[n];
              for (int i=0; i<n; i++)
                   names[i] = input2.next();
                   System.out.println(names);
    }However, when I tested this with a file containing "BOB","STEVE","MARK", n equaled 7 and my output was the names each separated by two empty lines.  There are other methods I can use to solve this problem, but I would really like to know why my delimiters are not working so I can use them in the future.
    Thanks,
    helixed
    Edited by: helixed on May 14, 2009 10:52 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Take a look at [Quantifiers in Java regex|http://java.sun.com/docs/books/tutorial/essential/regex/quant.html].
    I believe "[\",]+"{code} will get you the results you need.
    Edited by: nogoodatcoding on May 15, 2009 11:54 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • How to use regular expressions

    Hey ,
    I found my self getting troubled with using regex in java.
    I know that in order to use regex, i need to import two classes
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    but I become entangled with the implementation.
    I need to check if inserted string contains a number inside, so i build a pattern of regex. and compiled it. then i used matcher method. but from here all methods i use, i'm getting only the first digit of the number. ---> "sdasda25" i'm getting (after using group() ) only the digit 2.
    is there any method that i can pass over all chars in the string (by loop) and to check if that particular char isMatch for my pattern (That's the way to implement it in C#, and i thought that here it will be the same...).
    Tanx

    both of you were right, I didnt write a '+' at the end of my pattern
    thank you both

Maybe you are looking for

  • Will I be able to completely remotely control and access my Office Mac from my Macbook Air at home?

    I am in a bit of a dilemma and need some help from the community.  I have a Mac Mini running 16GB Ram 2.3 I7  and 1 TB Fusion Drive at my office, it is in Parrallels Coherence mode 100% of the time.   I have to run certain Windows apps from home.  I

  • Acrobat XI binder no longer works after update 11.0.09 whines about Flash

    Just since this recent update, four different computers cannot open a pdf  binder. It there a way to back up to previous version? As a precausion, I redownloaded flash player, and reinstalled. Same problem. Then I did a repair installation of Acrobat

  • Can't use mouse/keyboard/trackpad when waking iMac from sleep mode

    Basically as the title says. When I wake my iMac from sleep mode I am unable to use my keyboard/trackpad/mouse during the login window. Once the screen goes black by itself, after a minute or so I can then log in properly. Yes the keyboard/mouse/trac

  • Controlling Properties via Reference

    I have a cluster of numeric controls. I would like to control the properties (Disabled, Visible, Value, NumText.Format and NumText.Precision) of these individual controls by passing one reference from the cluster on the main vi, to a sub vi. Within m

  • Aperture is color shifting my exports

    I work with 48 bit TIFF images (color & b+w) imported from SilverFast 64 bit HDR images that were processed down to 48 bit. Tonight I became aware of a disturbing color cast which I initially assumed was a color space profile issue with Photoshop CS5