Regex Java Total String Length

假如想象 提交于 2019-12-24 12:08:37

问题


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.


回答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.




回答2:


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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/25544617/regex-java-total-string-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!