我正在努力使用java中的字符串split方法和插入符号(^)。
输入:
public class Coppier {
private static final String GETTER_EXPRESSION = "(get)([A-Z]\\w+)";
private static final String SETTER_EXPRESSION = "(set)([A-Z]\\w+)";
private static final String SETTER_REPLACE_EXPRESSION = "set$2";
private static final Pattern GETTER_PATTERN = Pattern.compile(GETTER_EXPRESSION);
private static final Pattern SETTER_PATTERN = Pattern.compile(SETTER_EXPRESSION);
private static void copy(Object from, Object to, Set<String> whitelist, Set<String> blacklist) {
for (Method method : from.getClass().getDeclaredMethods()) {
String name = method.getName();
if (whitelist != null && !whitelist.contains(name)) {
continue;
}
if (blacklist != null && blacklist.contains(name)) {
continue;
}
if (Modifier.isPublic(method.getModifiers()) && isGetter(method)) {
Method setter = getSetterForGetter(to, method);
if (setter != null)
try {
String setterName = setter.getName();
if (!(setterName.equals("setWalletAmount") || setterName.equals("setId"))) {
Object product = method.invoke(from);
setter.invoke(to, product);
}
} catch (IllegalAccessException e) {
//
} catch (InvocationTargetException e) {
//
}
}
}
}
public static void copy(Object from, Object to) {
copy(from, to, null, null);
}
private static boolean isGetter(Method method) {
return isGetter(method.getName());
}
private static boolean isGetter(String methodName) {
return GETTER_PATTERN.matcher(methodName).matches();
}
private static boolean isSetter(Method method) {
return isSetter(method.getName());
}
private static boolean isSetter(String methodName) {
return SETTER_PATTERN.matcher(methodName).matches();
}
private static String getSetterNameFromGetterName(String methodName) {
return methodName.replaceFirst(GETTER_EXPRESSION, SETTER_REPLACE_EXPRESSION);
}
private static Method getSetterForGetter(Object instance, Method method) {
String setterName = getSetterNameFromGetterName(method.getName());
try {
return instance.getClass().getMethod(setterName, method.getReturnType());
} catch (NoSuchMethodException e) {
return null;
}
}
}
预期输出:
value1^value2^value3\^value3part2
有人可以为此提供解决方案吗?
我尝试了多种解决方案但没有成功。
谢谢。
答案 0 :(得分:3)
根据您的评论,如果前面没有^
,您似乎只想在\
上进行拆分。在这种情况下,您可以使用negative look-behind机制(?<!...)
来测试我们尝试匹配的部分是否前面没有...
中描述的正则表达式。
在您的情况下,您可以使用它:
String[] values = yourLine.split("(?<!\\\\)\\^");
所以你要拆分
^
(我们需要将其\\^
转义为^
,因为它是正则表达式元字符之一),\
之前没有(?<!\\\\)
- 我们需要两次转义\
,一次在正则表达式中,一次在字符串文字中。