复杂的子字符串和字符串连接

Complicated substring and string 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 ## 中的内容如何)通过 return 句子的其余部分完成句子(使用名为 output 的变量或类似)。 如果target不是以输入开头(忽略PAIRED ##中内容不匹配),return null(output应该是null)。

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

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

要在输出中包含第二个 ## 组,您必须更改函数。

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

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

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#,这就是你想要的,如果我理解你的问题的话:)

您可以尝试像这样的正则表达式:

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"

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