0

Original regex: [v]\d+?\.\d

Captures the "v{N}.{n}" in strings where {N}/{n} is only a number. I try in code (java) but returns false.

Code:

  String content = "En este texto hay un documento v4.6.pdf";

  String pattern = "[v]\\d+?\\.\\d";

  boolean isMatch = Pattern.matches(pattern, content);
  System.out.println("The text contains 'v{N}.{n}'? " + isMatch);

Console:

The text contains 'v{N}.{n}'? false
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
S. Moreno
  • 526
  • 2
  • 7
  • 29
  • I don't think you want the `?` to be in your pattern. – DodgyCodeException Oct 03 '17 at 09:55
  • @DodgyCodeException because the number after the 'v' can be 1 or 99999999 with 'd+?' i get all the digit until the dot. – S. Moreno Oct 03 '17 at 10:02
  • But `\d+` already means "one or more digits". Isn't that exactly what you want? By using `"\\d+?"` you are saying *optionally* one or more digits. If that's the case, why not simply say "zero or more digits" - `"\\d*"` - but I think you'll always have a digit after the "v". – DodgyCodeException Oct 03 '17 at 10:11
  • You're right. I deleted de '"?"'. With '"\\d+"' if the string is '"doc v.3.pdf" 'returns false, the string must contain '"v{number}.{number}"' and using '"\\d*"' the String can be '"doc v.3.pdf"' and that's an error for user. – S. Moreno Oct 03 '17 at 10:25

2 Answers2

3

matches tries to match the entire String. You should use find method of Matcherinstead which tries to find a match. Or you could try matching the entire String using .* as postfix and prefix.

public static void main(String[] args) throws Exception {
    String content = "En este texto hay un documento v4.6.pdf";
    Pattern p = Pattern.compile("[v]\\d+?\\.\\d");
    Matcher m = p.matcher(content);
    if (m.find()) {
        System.out.println("found");
    }

}

O/P : found

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • @AvinashRaj - Yes, that's right. I was just emphasizing that the OP's regex is Ok but he was using the wrong method – TheLostMind Oct 03 '17 at 09:50
1

As others have pointed out, Pattern.matches() tries to match the whole string. I.e. as if there was a ^ at the beginning of the pattern and $ at the end. So you can do any of these two:

1. add .* to both end of the pattern:

String pattern = ".*[v]\\d+?\\.\\d.*";

2. Use Matcher.find():

String pattern = "[v]\\d+?\\.\\d";
Pattern regexPattern = Pattern.compile(pattern);
Matcher matcher = regexPattern.matcher(content);
boolean isMatch = matcher.find();
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49