Home > Blockchain >  Use Regular Expression To Identify Identical Strings in Java
Use Regular Expression To Identify Identical Strings in Java

Time:09-22

Sorry for probably a dumb question but I'm completely new to regular expression.

I have to identify whether some strings are identical given a pattern, is it possible to use regular expression to identify the pattern below? These strings should be treated the same in my project.

foo
foo(1)
foo(2)
foo(1)(1)
foo(1)(2)

foo(any number)(any number)(...)(...)

Any help? Thanks in advance.

CodePudding user response:

You can use the regex, [A-Za-z] (?:\(\d \))* which can be explained as follows:

  • [A-Za-z] : Any alphabets one or more times
  • (?:: Start of non-capturing group
    • \(: The character (
    • \d : One or more digits
    • \): The character )
  • ): End of non-capturing group
  • *: Zero or more times

CodePudding user response:

This should do the trick:

([A-z] )(:?\(\d \))*
  • ([A-z] ) captures the foo or any other text that consists of multiple letters and saves it in group 1
  • (:?\(\d \))* says (<1 or more digits>) 0 or more times

Regular expressions are not designed to compare strings to one another. You can match an input against a pattern.

You can test it against your input here: https://regex101.com/r/MRZxsS/1

  • Related