2

I have a piece of code that I can't make it working on Eclipse with Java 1.7 installed.

There is a regex expression I want to use to match and extract 2 strings from every match, so I am using 2 groups for this.

I have tested my expression in many websites (online regex testers) and it works for them bust it isn't working on my Java project in Eclipse.

The source string looks like anyone of these:

Formal Language: isNatural

Annotation Tool: isHuman%Human Annotator: isHuman

Hybrid Annotation: conceptType%Hybrid Annotation Tool: conceptType%Hybrid Tagset: conceptType

... and so on.

I want to extract the first words before the ":" and the word after for every match.

The regex I'm using is this:

(\w*\s*\w+):(\s+\w+)%{0,1}

And the snippet of code:

String attribute = parts[0];                            
Pattern pattern = Pattern.compile("(\\w*\\s*\\w+):(\\s+\\w+)%{0,1}");
Matcher matcher = pattern.matcher(attribute);
OWLDataProperty dataProp = null; 

if (matcher.matches()){
    while (matcher.find()){
        String name = null, domain = null;

        domain = matcher.group(1);
        name = matcher.group(2);

        dataProp = factory.getOWLDataProperty(":"+Introspector.decapitalize(name), pm); 

        OWLClass domainClass = factory.getOWLClass(":"+domain.replaceAll(" ", ""), pm);
        OWLDataPropertyDomainAxiom domainAxiom = factory.getOWLDataPropertyDomainAxiom(dataProp, domainClass);
        manager.applyChange(new AddAxiom(ontology, domainAxiom));
    }

Does anybody of you know why it's not working?

Many thanks.

Oscar M
  • 25
  • 5
  • Ok, I found how to get it working: just using .find() method without .matches() because in this case there could be multiple matches. Many thanks anyway! – Oscar M Jun 18 '15 at 11:12

1 Answers1

1

When using matches(), you are asking if the string you provided matches your regex as a whole. It is as if you added ^ at the beginning of your regex and $ at the end.

Your regex is otherwise fine, and returns what you expect. I recommend testing it regexplanet.com, Java mode. You will see when matches() is true, when it false, and what each find() will return.

To solve your problem, I think you only need to remove the if (matcher.matches()) condition.

Chop
  • 4,267
  • 5
  • 26
  • 58