我正在尝试从非结构化文本中检索程序后给出的名称,并以用户指定的格式显示它们“First MI.Last”或“Last,First MI”。有任何想法吗?到目前为止,它会检查字符串中是否存在逗号。如果是这样我想切换字符串中单词的顺序并删除逗号,如果有一个中间的首字母并且它不包含一个句点,我想添加一个。
if (entity instanceof Entity) {
// if so, cast it to a variable
Entity ent = (Entity) entity;
SName name = ent.getName();
String nameStr = name.getString();
String newName = "";
// Now you have the name to mess with
// NOW, this is where i need help
if (choiceStr.equals("First MI. Last")) {
String formattedName = WordUtils
.capitalizeFully(nameStr);
for (int i = 0; i < formattedName.length(); i++) {
if (formattedName.charAt(i) != ',') {
newName += formattedName.charAt(i);
}
}
}
name.setString(newName);
network.updateConcept(ent);
答案 0 :(得分:3)
使用正则表达式和String.replaceAll
:
"Obama, Barack H.".replace("(\\w+), (\\w+) (\\w\\.)", "$2 $3 $1")
结果为Barack H. Obama
。
答案 1 :(得分:2)
substring
这会更容易。这假定格式有效(您必须检查)。
//Separate the names
String newName;
String lastName = name.substring(0, name.indexOf(","));
String firstName = name.substring(name.indexOf(",")+1);
//Check for a space indicating a middle Name
//Check to see if the middle name already has the period if not add it
if(firstName.trim().contains(" ") && !firstName.contains(".")) {
firstName += ".";
}
newName = firstName + " " + lastName;
//Set the name to whatever you're using
请注意,如果允许名称包含"," " " or "."