Regex - Pattern for positive numbers

Hi,
I wanna check for positive numbers.
My code so far:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
boolean b = m.matches(); But I don't know how to check for positive numbers (including 0).
Thanks
Jonny

Just to make your life easier:
package samples;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
* @author notivago
public class Positive {
    public static void main(String[] args) {
        String input = "- 12 +10 10 -12 15 -12,000 10,000 5,000.42";
        Pattern p = Pattern.compile( "\\b(?<!-\\s?|\\.|,)([0-9]+(?:,?[0-9]{3})*(?:\\.[0-9]*)?)" );
        Matcher matcher = p.matcher( input );
        while( matcher.find() ) {
            System.out.println( "Match: " + matcher.group(1) );
}

Similar Messages

  • Regex Pattern For this String ":=)"

    Hello All
    True, this isn't the place to ask this but here it is anyway, if you can help please do.
    Can anybody tell me the regex pattern for this String:
    ":=)"
    Thanks
    John

    Yep, cheers it's ":=\\)"
    public class Test {
         public static void main( String args[] ) {
              String s = "one:=)two:=)three:=)four";
              String ss[] = s.split( ":=\\)" );
              for( int i=0; i<ss.length; i++ )
                   System.out.println( "ss["+i+"] = {" + ss[i] + "}" );
    }resulting in:
    ss[0] = {one}
    ss[1] = {two}
    ss[2] = {three}
    ss[3] = {four}

  • What's the regex pattern for regular English chars and numbers ...

    In Java String there is a matches(String regex) method, how can I specify the regex for regular English chars, I want it to tell me if the string contains non-English chars. The string is from an email, my application wants to know if the email contains any foreign characters, such as French, Spanish, Chinese ...
    So if the string looks like this : "Hi Frank, today is (5-7-2007), my address is : '[email protected]', email me ~ ! ^_^, do you know 1+2=3 ? AT&T, 200%, *[$300] | {#123}, / _ \;"
    It should recognize it as regular English characters.
    But if it contains any foreign language (outside of a-z) chars either western(Russian, Greek ...) or eastern languages (Japanese, Chinese ...), it should return false.
    I wonder how to write this "regex" ?
    Frank

    since french, english, and spanish use thesame
    alphabet, i don't know how you will have theregex
    for "english chars but not french or spanishones"
    :)Not true. Spanish has �
    KajAlso ll.ll was in 1994 dropped from the Spanish alphabet. :)No shit?
    What about ch and rr?

  • Creating a regex.Pattern for bulletin board tags

    I'm making a BB code system and have a problem making my patterns do as I like. At least when they are nested.
    For example, I'm using the this pattern:
    \\[b\\](.*?)\\[/b\\]And I'm replacing it with this:
    <b>{0}</b>If I apply this to the text:
    This is my text with bold words. Sometimes the tags [b]are nested[/b].It will turn into this (with a little cleaning.):
    This is my text with <b>bold</b> words. <b>Sometimes they are</b> nested.But what I really wanted, was this (with a little cleaning.):
    This is my text with <b>bold</b> words. <b>Sometimes they are nested</b>.I've tried a lot of different things, but always seems to run into a dead end. I'm hoping it's simply because I do not know enough about patterns, but I could really need some inspiration or guidance. Seems I'm running out of new things to try.
    Edited by: bsindu on Dec 5, 2007 1:44 AM

    It could be done using some replaceAll(...) operations:
    public class Foo {
        public static void main(String[] args) throws Exception {
            String text = "This is my text with bold words. Sometimes the tags [b]are nested[/b].";
            String s = text.
                        replaceAll("(\\[.\\][^\\[]+)\\[.\\]", "$1").    // replace the last tag of two successive 's
    replaceAll("\\[.\\]([^\\[]+\\[.\\])", "$1"). // replace the first tag of two successive 's
                        replaceAll("\\[(/?.)\\]", "<$1>");              // replace all and with <b> and </b>
            System.out.println(text);
            System.out.println(s);
    }Either a Pattern or a replaceAll(...) solution, both are a bit of a hack, if you ask me.

  • Need help verifying positive numbers

    I have a payroll program I've been working on for class the last few weeks. The most recent modification is that I need to confirm the hours and pay scale are entered in positive numbers. I've tried a while and an if...else statement and am getting an error telling me that I have an "illegal start" to the expression, and that the way I've written the statement is incompatible with boolean. Here is the code - I've colored the if...else statements red. The else statements don't give me an error, but the if statements do. (BTW, I've had the same problem trying to use a while statement.)
    I'm pretty sure it has something to do with how I've written the if statement, but I can't put my finger on it. Can someone help?
    Thanks,
    import java.util.Scanner; // program uses Scanner
    public class WeeklyPayrollTest
          public static void main(String args[])
            // create scanner to obtain input from command window
            Scanner input = new Scanner( System.in );
            // declare variables
            String exitPayroll;
            exitPayroll = "N";
            double numberHours = 0;
            double payRate = 0;
            // create a WeeklyPayroll object and assign it to currentPayroll
            WeeklyPayroll currentPayroll = new WeeklyPayroll();
            PayScale thisPay = new PayScale();
            while( exitPayroll.equalsIgnoreCase( "N" ) ) // begin while loop
                  // prompt for and input employee name
                  System.out.println( "Please enter employee name: " );
                  String nameOfEmployee = input.next(); // read user input
                  // prompt for and input hours worked
                  System.out.println( "Enter hours worked: ");
    {color:#ff0000}              if( input.nextDouble( <= 0 ) ) // compare input for positive numbers
                      System.out.println( "Only positive numbers are allowed. " +
                              "Please enter a correct number." ); // alert user positive numbers needed
                  numberHours = input.nextDouble(); // prompt for hours
                  else{
                  // prompt for and input hourly pay amount
                  System.out.println( "Enter hourly rate: ");
                  if(input.nextDouble( <= 0)) // compare input for positive numbers
                      System.out.println( "Only positive numbers are allowed. " +
                              "Please enter a correct number.") // alert user positive numbers are needed
                  payRate = input.nextDouble(); // prompt for rate of pay
                  else{
                  // call PayScale
                  double weeklyPay = thisPay.payScale( payRate, numberHours );
                  // call currentPayroll's displayMesage method and
                  // pass nameOfEmployee as an argument
                  currentPayroll.displayMessage( nameOfEmployee, weeklyPay );
    {color}             
                  System.out.println( "Would you like to exit this program? " +
                          "Enter Y for yes and N for no." );
                  exitPayroll = input.next(); // read user input
               } // end while loop
          System.out.println( "Thank you for using this payroll program." );        
        } // end main
    } // end class WeeklyPayrollTest

    if( input.nextDouble( )  <= 0) // compare input for positive numbers
                      System.out.println( "Only positive numbers are allowed. " +
                              "Please enter a correct number." ); // alert user positive numbers needed
                      numberHours = input.nextDouble(); // prompt for hours
    }This will through away the result. Try this
    numberHours = input.nextDouble;
    while ( input.nextDouble( )  <= 0) // compare input for positive numbers
                      System.out.println( "Only positive numbers are allowed. " +
                              "Please enter a correct number." ); // alert user positive numbers needed
                      numberHours = input.nextDouble(); // prompt for hours
    }

  • Parentheses for negative numbers in Excel 2011

    I couldn't find an appropriate section for this question.  Please forgive me if I posted it in the wrong place.
    I've been using Excel for Mac 2011 since it came out. Up until I updated to Yosemite, formatting negative numbers with parentheses appeared in the drop down menu, i.e., right click to get format cells, click "number" tab on top, click "number" on left. There is a dialog as to how you want negative numbers formatted. Parentheses used to be an option but no more. I attached a screen shot. Help!

    Same issue here with Excel 2011, problem started with the Yosemite installation and was not fixed with 10.10.1 nor the latest Microsoft update. 
    It's a big problem for accountants!
    On the Microsoft forum this gentleman replied with a workaround but it's a hassle to have to do this for each new spreadsheet.
    JonathanBuhacoff replied on November 9, 2014
    If you go to the dialog shown in Phillip's post and select "Custom" on the left side, you can enter this to get the parenthesis back:
    $#,##0;[Red](-$#,##0)
    Or this to use square brackets:
    $#,##0;[Red]"["-$#,##0"]"
    The format means  use $#,##0 for positive numbers and use [-$#,##0] in red for negative numbers.
    You could remove the hyphen too and just do this:
    $#,##0;[Red]"["$#,##0"]"
    I hope Apple takes note and pushes a fix for us.

  • Searching Site Content Using REGEX Patterns

    Intent: Detect content in SharePoint 2013 lists and libraries that matches a REGEX pattern, like social security numbers.
    SharePoint 2013 only exposes KQL and FQL languages. 
    http://msdn.microsoft.com/en-us/library/office/jj163973.aspx
    I am comfortable writing this as an App.  I do not know how to pass the search index through a REGEX match.  Perhaps there is a way to access the data on more of a server model instead of through the client APIs?

    Hi  Eric,
    For achieving your demand, you can write a Content Enrichment Web Service to extract regex patterns from a managed property.
    Here is a blog you can refer to:
    SharePoint 2013 Content Enrichment: Regular Expression Data Extraction:
    http://blogs.technet.com/b/peter_dempsey/archive/2013/12/04/sharepoint-2013-content-enrichment-regular-expression-data-extraction.aspx
    Reference:
    http://msdn.microsoft.com/en-us/library/office/jj163982.aspx
    http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2013/06/19/advanced-content-enrichment-in-sharepoint-2013-search.aspx
    Thanks,
    Eric
    Forum Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support,
    contact [email protected]
    Eric Tao
    TechNet Community Support

  • How to use multiple patterns for masking/format the input text

    Hi All,
    I am using Jdeveloper 11.1.1.5 and i have a requirement where i need to format my input Text value in these below patterns:-
    Format
    Example
    AA9A 9AA
    EC1A 1BB
    A9A 9AA
    W1A 1HQ
    A9 9AA
    M1 1AA
    B33 8TH
    A99 9AA
    AA9 9AA
    CR2 6XH
    DN55 1PT
    AA99 9AA
    For Example :-  If user puts value as EC1A1BB, it should automatically changed to EC1A 1BB
                                 if user puts value as W1A1HQ, it should be automatically changed to W1A 1HQ and so on..
    If it could have been one format , i might have followed this :- https://blogs.oracle.com/jdevotnharvest/entry/get_social_security_numbers_right
    But for multiple patterns i am not able to get through to the proper solution.
    Is there any way to achieve this ? Please suggest.
    Regards,
    Shah

    For the validation you should be able to use one regular expression where you add the logical or (|)  (check the doc http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html) between the groups. If none of the patterns matches you have an error.
    For the for formatting I'm not sure you can use only one expression.
    I suggest to write one method which does the checking on and the formatting may be using an array of patterns to check and iterate the patterns in a loop. Once you found a match you can read the needed format from another array (or an other dimension if you prefer to use a multidimensional array).
    Timo

  • Keep Original Position Numbers in Purchase Order Creation

    Hi community, i'm trying to solve the following problem in purchase order creation using BAPI_PO_CREATE1:
    I'm loading a file with several order numbers and positions to be created in R/3. This file has a structure similar to:
    OrderNumber;PositionNumber;Material;Quantity;Unit;.......
    The purchase order is created successfully, but i need to keep original position numbers in the order. i.e:
    Supposing this input file:
    1900;08;993322;10.00;KG.....
    1900;13;994455;12.00;KG.....
    the positions in purchase order are created as
    00010
    00020
    But i need positions to be created as:
    00008
    00013
    Any ideas?????
    Thanks you for your cooperation
    Leonardo

    Hi Leonardo,
       I doubt if that is possible.
    You can have the configuration set up to set the Item Number Interval to  step size like 5,10,15 etc,
    based on this value, your line item number will be
    5,10,15,20...
    10,20,30,40..
    15,30,45,60
    etc.
    to set this value, you should go to SPRO.
    Material Management->Purchase Order->Define Document Types
    Regards,
    Ravi Kanth Talagana

  • Patterns for charts

    I need to print a chart out in black & white and would like to use different patterns for the bars instead of colors. Does anyone know how to make the bars appear as different patterns instead of color?

    Numbers doesn't come with hashed patterns for black & white charts. You can make your own. Below are two patterns. You can flip the diagonal one to create a third. The difficult part in making one of these patterns is designing it to make a continuous pattern when attached side by side.
    Use the Graphic Inspector to change the bar color to a tiled image fill and put a solid line around the bars.
    /___sbsstatic___/migration-images/migration-img-not-avail.png
    /___sbsstatic___/migration-images/migration-img-not-avail.png

  • Regex pattern, filter delimiter in sql code

    Hi,
    The problem I'm having is that the regex pattern below is not catching the beginning "go" and ending "go" of a string.
    "(?iu)[(?<=\\s)]\\bgo\\b(?=\\s)"
    The idea is catching the "whole word", in this case the word is "go" so if the word is at the beginning of the string or at the end, i still want to include it.
    So, for example:
    "go select * from table1 go" -> should catch 2 "go"s but catches 0
    "go go# select * from table1 --go go" -> should also catch 2 "go"s but catches 0
    "go go select * from table1 go go" -> should catch 4 "go"s but catches 2
    I have the "[(?<=\\s)]" and the "(?=\\s)" so that the word "go" when next to a special character is not included, for example "--go".
    The problem is that this also negates the beginning and ending of the string.
    Code to test example: It should split at 1st, 2nd and last "go", but only splits at the 2nd "go".
    String s = "go go select * from table1 --go go";
    String delimiter = "go";
    String[] queries = s.split("(?iu)[(?<=\\s)]\\b" + delimiter + "\\b(?=\\s)");
    for (int i = 0; i < queries.length; i++) {
         System.out.println(queries[i]);
    I really need to fix this but I'm not having much success.
    Any help will be appreciated, thanks in advance.

    Yes,
    I prefer this one: Regex Powertoy (interactive regular expressions)
    It's not 100% perfect, but you can see with my example and this online tester that the 1st "go" is not matched. And this is a problem for me.
    I want to eliminate the special characters like "#go" or "-go" but i don't want to eliminate the end and start of string.

  • 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

  • Util.regex.Pattern documentation

    The 1.5 documentation for util.regex.Pattern defines quantifiers that are greedy, reluctant, or possessive. The definitions of these quantifiers seem to be the same. For example, X?, X??, and X?+ are each defined as "X, once or not at all." Is this a mistake? If not, what's that difference among greedy, reluctant, and possessive?

    It's not a mistake, it's just incomplete. A normal (greedy) quantifier matches as many times as it can, but will back off if necessary to achieve an overall match. A reluctant quantifier matches the minimum number of times that it has to, and only tries to match more if that's the only way to achieve an overall match. A greedy quantifier matches as many times as it can and never backs off, even if that makes an overall match impossible. Here's a demonstration:import java.util.regex.*;
    public class Test
      public static void main(String[] args)
        String input = "XXXXX";
        Pattern p1 = Pattern.compile("(X+)(X+)");
        Pattern p2 = Pattern.compile("(X+?)(X+)");
        Pattern p3 = Pattern.compile("(X++)(X+)");
        Matcher m = p1.matcher(input);
        if (m.matches())
           System.out.println("p1:\t" + m.group(1) + "\t" + m.group(2));
        m = p2.matcher(input);
        if (m.matches())
           System.out.println("p2:\t" + m.group(1) + "\t" + m.group(2));
        m = p3.matcher(input);
        if (m.matches())
           System.out.println("p3:\t" + m.group(1) + "\t" + m.group(2));
    p1:     XXXX    X
    p2:     X       XXXXIn p1, the X+ in the first group initially matches all five X's, then hands off to the second group. The X+ there has to match at least one X, but there are none left. So the first group gives up one of its X's, the second group matches it, and Bob's your uncle.
    In p2, the X+? has to match at least one X, so it does, then hands off to the second group, which happily gobbles up the rest of the input.
    In p3, the X++ matches all the X's, but refuses to back off and give the X+ in the second group the one X it needs, so the match fails.

  • Applying REGEX-pattern into XML File

    I have the following problem:
    I have an xml-file. let's say...
    <NODE><NODE1 attr1="a1" attr2="a2">
         <NAME> abc</NAME>
         <VERSION> 1.0</VERSION>
    </NODE1>
    <NODE2 attr1="a3" attr2="a4">
         <NAME> xyz</NAME>
         <VERSION> 3.1</VERSION>
    </NODE2></NODE>I need to know "HOW can I get the values of <NAME></NAME> and <VERSION></VERSION> without using DOM.
    Since my xml-file is pretty big and DOM will take much Memory, i want to avoid it.
    Can anybody suggest some "Regex pattern" so that i can apply it on the xml-file (after converting into String)
    Thanks in Advance

    That worked perfectly. I assumed ( insert comment here ) that the members of the Properties objects were Strings, and therefore followed the same rules where "\" characters are concerned.
    Thank you for pointing out the difference between the two objects, I am not sure how long it would have taken me to figure that out.
    Regards,
    John Gooch

  • RegEx Error for Huge File .. Please help , Its Urgent

    Hi all,
    I am getting following exception,
    does anyone know about it
    java.lang.IndexOutOfBoundsException: No group 1
    at java.util.regex.Matcher.group(Matcher.java:355)
    at java.util.regex.Matcher.appendReplacement(Matcher.java:585)
    at java.util.regex.Matcher.replaceFirst(Matcher.java:701)
    at XSLT_OnlyJava.<init>(XSLT_OnlyJava.java:84)
    at XSLT_OnlyJava.main(XSLT_OnlyJava.java:93)
    Exception in thread "main"
    I am parsing huge file with regex and replacing some part
    Thanks,
    Vinayak

    sorry for late
    This is my code
    text = contents.toString();
              String regex = "<tu.*?/tu>";
              Matcher matcher = Pattern.compile(regex,Pattern.CASE_INSENSITIVE|Pattern.DOTALL).matcher(text);
              while(matcher.find()){
                   tuvSegment = matcher.group();
                   String segRegex = "<seg>.*?</seg>";
                   Matcher segMatcher = Pattern.compile(segRegex,Pattern.CASE_INSENSITIVE|Pattern.DOTALL).matcher(tuvSegment);
                   if(segMatcher.find()){
                        SegVal = segMatcher.group();
                   String ReplsegRegex = "<seg />";
                   Matcher ReplsegMatcher = Pattern.compile(ReplsegRegex,Pattern.CASE_INSENSITIVE|Pattern.DOTALL).matcher(tuvSegment);
                   text = ReplsegMatcher.replaceFirst(SegVal);
    The text string contains teh .tmx file
    Thanks,
    Vinayak

Maybe you are looking for

  • Select row button not getting displayed in alv grid.

    Hi , As per my requirement I am using tab strip in module pool. Each tab strip is containing one ALV. And user can change delete or create one record when the alv is displayed. The same should be saved in the database and ALV should be refreshed. Whe

  • IPOD originally formatted for Windows...Now I have a IMAC

    My IPOD color 30gb was originally formatted and worked on a PC. I now own a IMAC and have transfered the music over. The music plays fine on the IMAC in ITunes, it down loads to the IPOD, but no sound comes from the IPOD. Do I need to reformat the IP

  • Lack of customer support follow up.

    I am facing a very large overage bill. I have called in 3 times to speak to customer service about it, have been promised follow ups 3 times, and never received a call back. 1st and 2nd occurrence were to be once monthly bill was processed. After no

  • IReports

    We are using ireports in our web project. When I am calling a report with subreport in it , report is coming with out the sub report. Any body who can help me to solve this problem.

  • Fill-In PDF form problems

    I filled in a job application document in Adobe Reader (as instructed by the HR website of the company I am applying to). When I re-opened the saved document in AR, the text was gone. When I opened the same version in Preview, the checkmarks were gon