限制正则​​表达式中的字符串长度

时间:2016-11-07 08:15:03

标签: java regex

我只是java正则表达式的初学者,我想限制搜索以找到具有特定长度的模式(例如:6),条件如下

[1-3][0-2][xs0][30Aa][xsu][.,]{6} or ^[1-3][0-2][xs0][30Aa][xsu][.,]$

这两个表达式都给出了不同的结果。不能同时返回相同的输出吗? 例如:2203s.对于第一个是假的,但对于第二个是真的。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

你的第一个正则表达式是:

Match a single character present in the list below [1-3]
Match a single character present in the list below [0-2]
Match a single character present in the list below [xs0]
Match a single character present in the list below [30Aa]
Match a single character present in the list below [xsu]
Match a single character present in the list below [.,] exactly six times.

你的第二个正则表示:

^ asserts position at start of the string
Match a single character present in the list below [1-3]
Match a single character present in the list below [0-2]
Match a single character present in the list below [xs0]
Match a single character present in the list below [30Aa]
Match a single character present in the list below [xsu]
Match a single character present in the list below [.,]
$ asserts position at the end of the string, 
    or before the line terminator right at the end of the string (if any)

所以...你的第一个正则表达式匹配长度为11的字符串,第二个正则表达式匹配长度为6的字符串。

[abc]是一个群组。它代表single a or b or c。您可以通过添加以下内容来修改组: *+{} [abc]*代表single character a or b or c, match 0 to inf times。将匹配例如:

  • a
  • b
  • abaa
  • abcabcabcaaaaa

+match at least one time
{6}表示匹配恰好6次。