1

I need the below regex to select only those of total size X:

[[JN]*P?[JN]*]N

EDIT:

e.g. for 6:

  • JJPNNN -> JJPNNN
  • ONNJNNNO -> NNJNNN
  • NPJNJNN -> NPJNJN, PJNJNN
  • NPJNN -> False

I need it to capture the group.

3
  • Will this work? ([[JN]*P?[JN]*]N){6}? Commented Aug 28, 2014 at 8:54
  • possible duplicate of regexp maximal length restrict Commented Aug 28, 2014 at 8:56
  • @BuhakeSindi No, it won't. that will repeat the whole pattern 6 times... Commented Aug 28, 2014 at 9:00

4 Answers 4

1

You can use lookahead to first check the length, like this:

(?=^.{6}$)[[JN]*P?[JN]*]N

Also, you seem to have too many brackets. To make the expression match your examples, you need to remove the outermost one:

(?=^.{6}$)[JN]*P?[JN]*N

Here is a small demo using ideone.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the size limiting

\{5,10}

something like that limits a size of 5~10

You should look up on it, there is tons of answered questions about this topic

Comments

0
String test = "123456"
if(test.match("^\w{6,6}$")
{
  //True if String has length of 6
}   

1 Comment

The OP wants a regex that will return true if it fits the pattern of [JN]*P?[JN]*]N and has a length of 6. Not one or the other.
0
public class Main {


    private static boolean match(String line) {
      Pattern p = Pattern.compile("^(?=[JNP]{6}$)[JN]*P?[JN]*N$");
      Matcher m = p.matcher(line);
      return m.matches();
    } 

    public static void main(String[] args) {

      System.out.println(match("JJPN"));
      System.out.println(match("JJPNNN"));
      System.out.println(match("NNJNNN"));
      System.out.println(match("NPJNJNN"));
      System.out.println(match("NPJNJNNNN"));

    }
}

out

false
true
true
false
false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.