【发布时间】:2016-01-04 11:07:51
【问题描述】:
我有一个要求,创建一种降价标签以在创建PDF's 时将 bold [N] 和 italic [C] 文本放入给定的字符串中IText.
所以,给定这个字符串:
String toCheck = "Example [N]bold text[N] other example [C]italic text[C]";
应该结果:
示例粗体文本其他示例斜体文本
好吧,我们走吧:
我有一个字体类型的枚举:
private enum FontType {
BOLD, ITALIC, NORMAL
}
为了实现这一点,我想创建一个LinkedHashMap<String, Enum> 来插入具有相应字体类型的字符串片段(稍后将转换为com.itextpdf.text.Chunk 并插入单个com.itextpdf.text.Paragraph。
那么我怎样才能达到这样的LinkedHashMap结果呢??
pos String enum
0 "Example " NORMAL
1 "bold text" BOLD
2 " other example " NORMAL
3 "italic text" ITALIC
我创建了一个自定义的Iterator,它为我提供了标签位置:
public class OwnIterator implements Iterator<Integer>
{
private Iterator<Integer> occurrencesItr;
public OwnIterator(String toCheck, String[] validPair) {
// build regex to search for every item in validPair
Matcher[] matchValidPair = new Matcher[validPair.length];
for (int i = 0 ; i < validPair.length ; i++) {
String regex =
"(" + // start capturing group
"\\Q" + // quote entire input string so it is not interpreted as regex
validPair[i] + // this is what we are looking for, duhh
"\\E" + // end quote
")" ; // end capturing group
Pattern p = Pattern.compile(regex);
matchValidPair[i] = p.matcher(toCheck);
}
// do the search, saving found occurrences in list
List<Integer> occurrences = new ArrayList<>();
for (int i = 0 ; i < matchValidPair.length ; i++) {
while (matchValidPair[i].find()) {
occurrences.add(matchValidPair[i].start(0)+1); // +1 if you want index to start at 1
}
}
// sort the list
Collections.sort(occurrences);
occurrencesItr = occurrences.iterator();
}
@Override
public boolean hasNext() {
return occurrencesItr.hasNext();
}
@Override
public Integer next() {
return occurrencesItr.next();
}
@Override
public void remove() {
occurrencesItr.remove();
}
}
我已经检查了标签是否平衡,我可以得到所有标签位置:
String[] validPair = {"[N]", "[C]" };
OwnIterator itr = new OwnIterator(toCheck, validPair);
while (itr.hasNext()) {
System.out.println(itr.next());
}
但是在得到所有位置后无法弄清楚如何区分每个部分并分配正确的枚举值。
一些想法? 也许我的方法有误,或者有人可以看到更好的方法?
【问题讨论】:
-
你有没有想过使用正则表达式组?以javamex.com/tutorials/regular_expressions/… 为例。
-
@RatshiḓahoWayne 如果你看一下迭代器,正则表达式已经被使用了......你的意思是另一种方式?我使用正则表达式很糟糕:$
-
Regex 太复杂了,请看我贴出来的答案
标签: java regex dictionary split itext