• Post Reply Bookmark Topic Watch Topic
  • New Topic

regex  RSS feed

 
Jan Kwiatkowski
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Can anyone solve the following problem?
I need regex that will match to 4 character string that contains for example two "a" character(not always following each other). I mean:

America (contains double "a" so there would be a match)
Aaron (there would be a match too)
Antarctica (no match, three of "a")

cheers,
J.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

We don't simply hand out answers here, but if you show us what you have got already, we shall be only too pleased to help.
I trust you have been through the Java� Tutorials?
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A regex for it would "look" like this (when using String.matches(..)): "match zero or more characters other than 'a' followed by an 'a' followed by zero or more characters other than 'a' followed by another 'a' and ending with zero or more characters other than 'a'".

Try to translate this into a regex.
 
Jan Kwiatkowski
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for help. It was really handy advice
The regex looks like this: "[^a]*a[^a]*a[^a]*"

Thanks once more
cheers,
J.
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jan Kwiatkowski:
Thanks for help. It was really handy advice


Yes, well done, Piet and Jan
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jan Kwiatkowski:
Thanks for help. It was really handy advice
The regex looks like this: "[^a]*a[^a]*a[^a]*"

Thanks once more
cheers,
J.


You're welcome. And to make it case insensitive, you could do it like this:

which is a rather long-winded solution. This is a shorter version of the above:

Wherever you place the i-flag "(?i)" in your regex, from thereon case insensitive matching is applied. You could even tell it to stop matching case insensitive by inserting the stop-flag "(?-i)" in your regex.

For example, these are the same regexes:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!