Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

pattern Match without using Pattren or RegulaExpression

 
Osgar ali
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • 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
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • 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
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic