Justin
Justin

Reputation: 4539

java regex to capture any number of periods within a string

I am trying to match on any of the following:

$tag:parent.child$
$tag:grand.parent.child$
$tag:great.grand.parent.child$

I have tried a bunch of combos but not sure how to do this without an exp for each one: https://regex101.com/r/cMvx9I/1

\$tag:[a-z]*\.[a-z]*\$

I know this is wrong, but haven't been able to find the right method yet. Help is greatly appreciated.

Upvotes: 1

Views: 234

Answers (4)

user11809641
user11809641

Reputation: 895

Not sure if this is what you want, but you can make a non-capturing group out of a pattern and then find that a certain number of times:

\$tag:(?:[a-z]+?\.*){1,4}\$
  • \$tag: - Literal $tag:
  • (?:[a-z]+?\.*) - Non-capturing group of any word character one or more times (shortest match) followed by an optional literal period
  • {1,4} - The capturing group appears anywhere between 1-4 times (you can change this as needed, or use a simple + if it could be any number of times).
  • \$ - Literal $

I normally prefer \w instead of [a-z] as it is equivalent to [a-zA-Z0-9_], but using this depends on what you are trying to find.

Hope this helps.

Upvotes: 0

CAustin
CAustin

Reputation: 4614

The following pattern will match any periods within a string:

\.

Upvotes: 0

David Conrad
David Conrad

Reputation: 16359

You can use \$tag:(?:[a-z]+\.)*[a-z]+\$

  • \$ a literal $
  • tag: literal tag:
  • (?:...) a non-capturing group of:
    • [a-z]+ one or more lower-case letters and
    • \. a literal dot
  • * any number of the previous group (including zero of them)
  • [a-z]+ one or more lower-case letters
  • \$ a literal $

Upvotes: 2

Andreas
Andreas

Reputation: 159086

Your regex was: \$tag:[a-z]*\.[a-z]*\$

You need a repeating group of .name, so use: \$tag:[a-z]+(?:\.[a-z]+)+\$

That assumes there has to be at least 2 names. If only one name is allowed, i.e. no period, then change last + to *.

Upvotes: 3

Related Questions