0

I want to get two decimals from a string using a Regex but I get only the first.

getGroupCount is correct but I get always {1} and I don't know why. I'm using GWT 2.5. Here is my code:

private void readOffset(){
    RegExp regExp = RegExp.compile("(\\{\\d\\})");

    MatchResult matcher = regExp.exec("(cast({1} as float)/{24})");

    String val1 = matcher.getGroup(0);
    String val2 = matcher.getGroup(1);
}

Why might this be happening?

hichris123
  • 10,145
  • 15
  • 56
  • 70
user1573659
  • 29
  • 1
  • 4

3 Answers3

1

The operator \d will only yield 1 digit. If you want to get two, you would need to use \d{2}. If you need to match more, you would need to use \d+, where + means 1 or more repetitions of.

Something like so worked for me (Java though, not exactly GWT):

        String str = "(cast({1} as float)/{24})";
        Pattern p = Pattern.compile("(\\{\\d+\\})");
        Matcher m = p.matcher(str);         
        while(m.find())
        {
            System.out.println(m.group(1));
        }

Yields: {1} and {24}

npinti
  • 51,780
  • 5
  • 72
  • 96
0

To learn how to use Regex in GWT client side please go through the Unit test cases in GWT for Regex. Reference - GWT Unit Test for Regex

Also you should be using RegExp and MatchResult from com.google.gwt.regexp.shared.

appbootup
  • 9,537
  • 3
  • 33
  • 65
  • Can you just not replicate this in GWT - http://stackoverflow.com/questions/1623221/how-to-find-a-number-in-a-string-using-javascript – appbootup Jan 09 '13 at 15:06
0

im to stupid for the regex so i solved it quick and dirty:

private void readOffset(){
    String offset = manager.get("offset");

    String v1 = offset.substring(offset.indexOf("{")+1, offset.indexOf("}"));
    String v2 = offset.substring(offset.lastIndexOf("{")+1, offset.lastIndexOf("}"));

    multiplikator.setValue(v1);
    divisor.setValue(v2);

    /*
    RegExp regExp = RegExp.compile(".*({\\d+}).*", "g");
    MatchResult matcher = regExp.exec(offset);
    boolean matchFound = (matcher != null);

    if(matchFound == true && matcher.getGroupCount() == 2){
        String val1 = matcher.getGroup(0);
        String val2 = matcher.getGroup(1);

        multiplikator.setValue(matcher.getGroup(0));
        divisor.setValue(matcher.getGroup(1));
    }else{
        multiplikator.setValue("1");
        divisor.setValue("1");
    }
    */
}

better solutions are welcome :(

user1573659
  • 29
  • 1
  • 4