Sandeep
Sandeep

Reputation: 722

Java regex find method returns false for matching roman numerals

I am trying to create a regex pattern in java to match list text which has certain attributes. For example :

(i) hello stackoverflow

(iv) hello user

The list can either match (i) or i). I have arrived at a pattern using my understanding of regex and tested that version in an online tool and it returns the correct result. However when i implement it in java the pattern matcher returns false for find method.

Here is the psudo-code:'

String text = "(i) hello";
String romanNumeralsRegex = "^(\\(|\\[)?((v|x)?i[xv]|(xv|v|x)?i+|(xv|v|x))((\\)|\\]|\\.))";
Pattern pattern = Pattern.compile(romanNumeralsRegex );
Matcher matcher = pattern.matcher(text);
System.out.println(matcher.find());

The matcher.find() method is returning false. As per my understanding the matcher should return group(0) as (i). I don't know where I have gone wrong. Requesting help from the community here

Thanks in advance.

Upvotes: 3

Views: 81

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

Everything looks correct to me, except you need to call Matcher#group after you call Matcher#find:

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

Output:

(i)

Upvotes: 2

Related Questions