复杂的子串和字符串连接

时间:2015-07-01 14:09:53

标签: java string algorithm substring concatenation

String target = "When user fills in #this# in form #that#"
// I have my function in removing all content in between paired "##"
String processedTarget = "When user fills in ## in form ##"
// processedTarget is generated using the function from target

String input = "When user fills in #test#"
// Same function is used in here to process input
String processedInput = "When user fills in ##"
//processedInput is generated using the same way

以简单的方式(仅使用Java内置方法),如何生成" in form #that#"? 目的是将用户输入与目标进行比较,无论输入的"##"之间的内容如何,​​但应该呈现"##"之间从目标中留下的内容。

如果目标以输入开头(无论PAIRED ##中的内容如何)通过返回句子的其余部分(使用名为output或类似的变量)来完成句子。 如果目标不是以输入开头(忽略PAIRED ##中内容的不匹配),则返回null(output应为null)。

在示例中,输入与目标匹配。

3 个答案:

答案 0 :(得分:1)

您可以尝试使用正则表达式:

String regex = "When user fills in #[^#]*# in form #[^#]*#(.*)"

然后将其用作Pattern

Pattern pattern = Pattern.compile(regex);

还有一个可用于检索结果的匹配器,例如:

Matcher matcher = pattern.matcher("When user fills in #null# in form of #void#, he sucks");

然后您可以使用matcher.matches()matcher.group(1)来获取结果,该结果应为:

", he sucks"

我不确定这是不是你想要的,因为我真的不知道你的意图。

答案 1 :(得分:0)

您需要将用户输入转换为正则表达式:

String target = "foo #word# bar #word# bar #word# foo #word#";
String input = "bar #first# bar #another#";

String regex = input.replaceAll("#[^#]*#", "#[^#]*#");
String output = target.replaceAll(regex, "");

output变成foo #word# foo #word#,如果我理解你的问题,这就是你想要的:)

答案 2 :(得分:-1)

您可以使用String.replaceFirst(String, String)processedInput删除processedTarget

要在输出中添加第二个##组,您必须更改自己的功能。

String processedInput = "When user fills in ##";
String processedTarget = "When user fills in ## in form #that#"; // Keep the second
String output = processedTarget.replaceFirst(processedInput, "");