Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

pattern Match without using Pattren or RegulaExpression

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I am trying to write a java code to do a string pattern search. I don't want to use any Pattern or Regular Expression. Can someone give me some input how I can do that.

Here is an example:

String is: aaBaBaaaBaaa

if characters aBa is found in the above sting print B, if aaa is found print A.

Example: aaBaBaaaBaaa will out put BAA.

aaaBaBaaaaBBaBaBa will out put ABAB

Thanks
Oskar
 
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Osgar,

perhaps one of the best ways to search a string for a specific pattern without using regular expression is the Knuth-Morris-Pratt algorithm. It's to complicated to explain here in a few lines but I'm sure you'll find lots of information about it in the internet. Good luck ;-)

Marco
 
Sheriff
Posts: 22579
122
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Loop through the string and use String.regionMatches. If there is a match, don't just jump to the next character but go forward match.length(), where match is either aBa or aaa.

Altenatively, you could use a combination of indexOf calls:

You would have to test to see which of these two algorithms is faster, but I think it also depends on the number of occurrances.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic