我有一个名为'string1'的字符串,
string1 = "Mr. Jorge Alexa Narvaez is a former Canadian cricketer and a politician.";
我还有另一个名为'string2'的字符串,只有字符串被'<NOUN> and </NOUN>
'标记所包围,用空格分隔。
string2 = "<NOUN>Jorge Alexa Narvaez</NOUN> <NOUN>Canadian</NOUN>";
请注意,第二个字符串可以包含任何名词标记的单词(基于'string1',例如:如果string1有3个名词,则string2将具有由名词标签包围的相同3个名词)
我想在'string1'中添加标签,并按如下方式生成string1,
string1 = "Mr. <NOUN>Jorge Alexa Narvaez</NOUN> is a former <NOUN>Canadian</NOUN> cricketer and a politician.";
我只想将{Jorge Alexa Narvaez'和'Canadian'替换为<NOUN>Jorge Alexa Narvaez</NOUN> and <NOUN>Canadian</NOUN>
有人可以告诉我怎么做吗?
答案 0 :(得分:1)
可以按照以下方式完成,
Pattern p = Pattern.compile("<NOUN>(.*?)</NOUN>");
Matcher m = p.matcher(string2);
while(m.find()) {
string1= string1.replaceAll(m.group(1),m.group(0));
}
答案 1 :(得分:0)
几个问题:
如果它只包含标签,那么粗略的方法是
执行此操作的示例代码:
{
String string1 = "Mr. Jorge Alexa Narvaez is a former Canadian cricketer and a politician.";
String string2 = "<NOUN>Jorge Alexa Narvaez</NOUN> <NOUN>Canadian</NOUN>";
String[] list = string2.split("(<NOUN>|</NOUN>)");
for (String str : list)
{
if (str.trim().isEmpty())
{
continue;
}
string1 = string1.replace(str, "<NOUN>" + str + "</NOUN>");
}
System.out.println(string1);
}
如果您有关于如何生成string2的更多详细信息,那么有更好的,有组织的方法来执行此操作。
答案 2 :(得分:0)
它在c#中......希望你将它正确转换为java
string s="<NOUN>Jorge Alexa Narvaez</NOUN> <NOUN>Canadian</NOUN>";
string s1="Mr. Jorge Alexa Narvaez is a former Canadian cricketer and a politician.";
foreach(Match m in Regex.Matches(s,@"(?<=<NOUN>).*?(?=</NOUN>)"))
s1=Regex.Replace(s1,m.Value,"<NOUN>$0<NOUN>");
答案 3 :(得分:0)
我尝试了以下代码,它运行得很好。您可以使用Stringbuffer而不是String类来优化它。
import java.util.StringTokenizer;
public class StringManipulation {
String temp = "<NOUN>Nitin<NOUN> <NOUN>test<NOUN>";
String finalString ="HeI am Nitin and I want to test seomthing";
public void doIt(){
StringTokenizer x = new StringTokenizer(temp, " ");
while (x.hasMoreTokens()){
String token = x.nextToken();
String findword = token.replaceAll("<NOUN>", "");
String findword1 = findword.replaceAll("</NOUN>", "");
String modifiedString = finalString.replaceFirst(findword1, "<NOUN>"+findword1+"</NOUN>");
this.finalString = modifiedString;
}
System.out.println(finalString);
}
/**
* @param args
*/
public static void main(String[] args) {
new StringManipulation().doIt();
}
}