1 25 26 package net.killingar.wiki.parser; 27 28 import net.killingar.wiki.Node; 29 import net.killingar.wiki.Parser; 30 import net.killingar.wiki.impl.AbstractNode; 31 import net.killingar.wiki.impl.LineNode; 32 import net.killingar.wiki.impl.LiteralNode; 33 import net.killingar.wiki.impl.SimpleNode; 34 35 44 public class ReplaceParser implements Parser 45 { 46 private String data; 47 private int currentOffset = 0; 48 private int line = -1; 49 private int stage = 0; 50 51 private String search, replace; 52 53 56 public ReplaceParser(String inSearch, String inReplace) 57 { 58 search = inSearch; 59 replace = inReplace; 60 } 61 62 private void setParsableString(String inParsableString) 63 { 64 data = inParsableString; 65 } 66 67 public void setSource(Object o) 68 { 69 if (o instanceof String ) 70 setParsableString((String )o); 71 else if (o.getClass() == SimpleNode.class || o.getClass() == LineNode.class) 72 { 73 setParsableString(((AbstractNode)o).getText()); 74 line = ((AbstractNode)o).getLineNumber(); 75 } 76 else 77 throw new IllegalArgumentException ("unsupported type "+o.getClass()); 78 79 currentOffset = 0; 80 } 81 82 public boolean hasMore() 83 { 84 if (data == null) 85 return false; 86 87 return currentOffset < data.length(); 88 } 89 90 public Node next() 91 { 92 if (currentOffset >= data.length()) 93 throw new IllegalStateException ("past end"); 94 95 Node n = null; 96 97 int foo = currentOffset; 98 99 if (stage == 0) 100 { 101 foo = data.indexOf(search, currentOffset); 102 103 if (foo != -1) 104 { 105 n = new SimpleNode(data.substring(currentOffset, foo), line, currentOffset, foo); 106 stage++; 107 108 currentOffset = foo+search.length(); 109 } 110 else 111 { 112 foo = data.length(); 113 n = new SimpleNode(data.substring(currentOffset, foo), line, currentOffset, foo); 114 115 currentOffset = data.length(); 116 } 117 } 118 else { 120 stage = 0; 121 n = new LiteralNode(replace, line, currentOffset, foo); 122 } 123 124 return n; 125 } 126 127 public static final void main(String [] args) 128 { 129 ReplaceParser p = new ReplaceParser("foo\n\\{divider}", "<hr/>"); 130 p.setSource("Den coola privata sidan för hailkören möller! Jag testar massa shit med forumet, så ni kommer bli irriterade på hur ofta den här sidan ändras :P\n\n{divider}\nfoobar!"); 131 132 while(p.hasMore()) 133 { 134 System.out.println(p.next()); 135 } 136 } 137 } 138 | Popular Tags |