-1

I'm relatively new to Regex and feel that I've missed something important.

My pattern id='([a-zA-Z0-9]+)' works for a C# version of the project I've made but doesn't in the java version. I'm trying to grab the word "frame" from the string IFrame[id='frame'] .leftObject.

Here is a link to the pattern and my code that I'm using. https://regex101.com/r/MmkGZq/2

        String pattern = "id='([a-zA-Z0-9]+)'";
        Pattern r = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
        Matcher m = r.matcher(jQuerySelector);    //<---jQuerySelector = "IFrame[id='frame'] .leftObject"
        System.out.println(m.matches());          //<---returns false
        return m.group(1);

Is it something to do with Regex in C# reading differently to Regex in Java?

Kyle
  • 43
  • 1
  • 6
  • As per the linked question, change `m.matches()` to `m.find()` for a partial match (i.e. the entire string doesn't have to match the expression). – ProgrammingLlama Sep 06 '19 at 04:50

1 Answers1

0

Your expression seems to be working OK, maybe this expression might also work, I'm guessing you wish to extract the frame:

(?<=id=')[^']*(?=')

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

    public static void main(String[] args){

        final String regex = "(?<=id=')[^']*(?=')";
        final String string = "IFrame[id='frame'] .leftObject";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println(matcher.group(0));
        }

    }
}

Output

frame

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Emma
  • 27,428
  • 11
  • 44
  • 69
  • 2
    While this might work, it is just boiler plate code and doesn't attempt to explain what the OP is actually doing wrong. – Tim Biegeleisen Sep 06 '19 at 04:49
  • 1
    @Emma Didn't work either. Still not finding any matches & prints out false on `m.matches()`. – Kyle Sep 06 '19 at 05:09
  • 1
    @Emma Yes. `frame` is what I am trying to extract. – Kyle Sep 06 '19 at 05:19
  • 1
    I just tried using find. While it prints out `true`, when I do a check against it it returns false... I'm very confused. `System.out.println(m.find());` prints out 'true'. `if (m.find()) { return m.group(0); }else{ return "";}` reads as 'false'. Any idea why? – Kyle Sep 06 '19 at 05:33