Java regex

Hi, I'm pretty new to Java, coming from a JavaScript background. I'm currently doing (or trying) a few challenges from a Java book that I have (Java Programming - For The Absolute Beginner). The challenge that I'm currently attemping asks me to write an application that calculates a 5% tax for any given amount, the problem is... I want to make my program accept both integers and real numbers. I thought it would be pretty straightforward to write two regular expressions, one to match an integer (1-99) and one to match a real number (0-99.0-99), and then, depending on whether the user input was a match to an integer or a real number; convert the match to either an int or float, then assign it to the appropriate variable type instance, I'm having a few problems :)
Here's my code (I know it contains loads of errors, lol) -
Challenge01.java
import java.io.*;
import java.text.DecimalFormat;
import java.util.regex.*;
public class Challenge01 {
  public static void main(String args[]) {
    //Declaration
    int anyPrice;
    float fivePercentTax;
    //Assignment
    anyPrice = 0;
    fivePercentTax = 0.05F;
    String value;
    //Regex
    Pattern intPattern = Pattern.compile("d");
    Pattern floatPattern = Pattern.compile("d.d+");
    //Declaration of a buffer
    BufferedReader reader;
    //Create an instance of the buffer
    reader = new BufferedReader(new InputStreamReader(System.in));
    //Format the data
    DecimalFormat twoDigits = new DecimalFormat("0.00");
    //Prompt for user input
     System.out.print("\t Enter a number:\t");
      value = reader.readLine();
      if value == intPattern {
         anyPrice = Integer.parseInt(value);
      else anyPrice = Float.parseFloat(value);
    System.out.print("\t" anyPrice);
}Thanks in advance for any help :)

Saying "it has problems" doesn't mean much to anybody. What does it do and what it is supposed to do?
You may want to take a look at your regular expressions.
Pattern intPattern = Pattern.compile("d");Will match the letter 'd' once. You have to escape the 'd' using \\d in order for it to match digits. Secondly, add a '+' to make it match one or more characters instead of only one.
Also, this line
else anyPrice = Float.parseFloat(value);won't work. An int cannot be assigned a float value.
Edited by: codingMonkey on 2008/10/15 03:59

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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

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

  • 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

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

  • Regular Expressions with Java Regex

    Hi,
    I'm playing around with regex and there's something I can't get to work. What I need, is to capture words between 2 other words and the words captured has to be higher than 5 characters, so for example:
    Pattern "Just testing on something with regular expressions" and suppose I'll try to match all the words between "testing" and "regular", then only the word "something" should come out because "on" and "with" are not larger than 5 chars.
    Now I'm quite new to regexps and I know that ((?<=\btesting\b).*(?=\bregular\b)) will return " on something with "
    But I can't seem to come up with an expression that would only output the word "something". I've tried a few expressions like ((?<=\btesting\b)((?:[\s\w{1,3}])*(\b\w{4,}\b)*(?:[\s\w{1,3}])*)*(?=\bregular\b)) which also returns " on something with " The others I tried would either return the whole " on something with " or return "Not Found!"
    Does anyone have a tip for me? I'm well aware that it's not too hard to do something like this in Java, but I'm really looking to study regular expressions and would like to accomplish this using a regular expression.
    The Java program I use is the following:
    C:\Program Files\Java\jdk1.5.0_16\bin>java RegexTest "((?<=\btesting\b).*(?=\bregular\b))" "Just testing on something with regular expressions"
    public class RegexTest {
         public static void main(String[] args) {
              Pattern RegexCompile = Pattern.compile(args[0]);
              Matcher m = RegexCompile.matcher(args[1]);
              boolean found = m.find(); // Perhaps there's another function to find () that would do the job?
              if (found)
              System.out.println(m.group()); // Perhaps group() is not the right function for this case?
              else
              System.out.println("Not Found!");
    Edited by: dli2k3 on Sep 19, 2008 11:32 AM
    Edited by: dli2k3 on Sep 19, 2008 11:33 AM

    You're talking about a two-stage operation: find everything between those two words, then filter out anything that's less than five letters long. There's no single regex that will accomplish all that in one step.
    By the way, please use &#x7B;code} tags when you post source code.

  • Java + Regex (Searching one or more words within quotes)

    Hi Everyone,
    I have the following text:
    The brown "cow" jumped over the "contributor licensing agreement" and went to "Burger King" to order chicken wings.
    The text above may change. This is the input text. In the input text, I want to find and print out all phrases that are inbetween quotes. I tried the following:
    Pattern pattern = Pattern.compile("\"(.*)\"");
    Matcher matcher = pattern.matcher(paragraph);
    while(matcher.find()){
        String theMatch=matcher.group();
        System.err.println("Found: "+theMatch);
    }The regex expression works in my regex coach program (which helps me test regex on input strings). In the Java code, however, the application only finds "cow", not "contributor licensing agreement" or "Burger King." What do I need to do in order to find those other two phrases? I want to use this to parse out and find all words or phrases in a document that are inbetween quotes.
    What am I doing wrong??
    jetcat33

    how about using a "reluctant" quantifier "?"
        Pattern pattern = Pattern.compile("\".*?\""); // note the question mark
        Matcher matcher = pattern.matcher(paragraph);
        while(matcher.find()){
            String theMatch=matcher.group();
            System.err.println("Found: "+theMatch);
        }

  • 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

Maybe you are looking for

  • LiveCycle Version 8-PDF Preview not available

    I am designing forms in LiveCycle version 8.0. The PDF Preview is not available. The help file says it's because I don't have Acrobat installed. I have Acrobat Professional version 8 installed. How do I get the PDF preview?

  • Fingerprint windows 7-64 login problem

     I have new installation of windows 7 64. After applying the exchange profile the fingerprint stop working for windows login. It works for power on and for entering the software control panel. I remove it and re install without success. Appreciates

  • Final Cut Pro laggs my mac pro???

    Hey guys wats up...Well im new to Mac/Video I have a Mac Pro and using a Canon XH-G1 and I just got final cut studio 2 last week just getting use to it... Im an absolute newb to all of this. Im just wondering, when i shot my HD footage and was editin

  • I cannot download my pics from my flash drives into Photoshop elements 11.

    I cannot dowmload my pics from my flash drives into Photoshop elements 11. Each time I try it gets to about 15% and then Photoshop crashes. It is not the flash drives as other programmes on my computer open them without a problem. Please help

  • No lyrics in the new music app?

    Very disappointed, the new music app in iOS5 hide my songs lyrics...that was one of my favorite features in the old iPod app! And now no multitouch gestures for iPad 1 user...I am very sad and disappointed. Somebody know about a good music player app