0

I am just a beginner in java regex and I want to restrict a search to find a pattern of a particular length (eg:6) with the conditions below

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

Both the expressions give different results.Shouldn't both return the same output? eg: 2203s. is false for the first but true for the second.

Thanks in advance :)

sparkstar
  • 195
  • 1
  • 1
  • 10
  • The `{6}` in `[.,]{6}` only quantifies `[.,]`, these regexps are not identical. I guess you are using them with `matches()`, right? – Wiktor Stribiżew Nov 07 '16 at 08:17
  • Yes. If I remove {6} ,will it restrict the search to strings of length 6? (It will still search for the pattern in a longer string and return true i guess). Is there any other way to restrict the length besides using ^ $? – sparkstar Nov 07 '16 at 09:04
  • 1
    Sure, with lookaheads, `^(?=.{6}$)....` – Wiktor Stribiżew Nov 07 '16 at 09:07

1 Answers1

0

Your first regex says:

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.

Your second regex says:

^ 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)

So... Your first regex matches strings of length 11, and the second one matches strings of length 6.

[abc] is a group. It stands for single a or b or c. You can modify a group by adding: *, + or {}.
[abc]* stands for single character a or b or c, match 0 to inf times. Will match for example:

  • a
  • b
  • abaa
  • abcabcabcaaaaa

+ says match at least one time,
{6} says match exactly 6 times.

xenteros
  • 14,275
  • 12
  • 47
  • 81
  • No need copy/pasting such machine-like explanations that can be easily obtained at https://regex101.com/r/Gn4NRk/1 and https://regex101.com/r/Gn4NRk/2. – Wiktor Stribiżew Nov 07 '16 at 08:20