我目前正试图解释一些我为某些东西编写的代码。我想拆分的信息看起来像这样:
{hey=yes}TEST
我想要实现的目标是在'}'之间分割上面的字符串。和' T' (T,可以是任何字母)。我追求的结果是(伪代码):
["{hey=yes}", "TEST"]
怎么会这样做?我知道基本的正则表达式,但从来没有用它来在字母之间分割字符串。
更新
为了分割字符串,我使用的是String.split方法。要知道是否有更好的方法来做这件事。
答案 0 :(得分:2)
您可以使用String的split方法,如下所示:
String str = "{hey=foo}TEST";
String[] split = str.split("(?<=})");
System.out.println(split[0] + ", " + split[1]);
它拆分字符串并打印出来:
{hey = foo},TEST
?<=}
,是在角色}
和保持角色的同时进行拆分。默认情况下,如果您只是分割一个字符,它将被拆分删除。
这个其他答案提供了使用split方法时所有选项的完整说明: how-to-split-string-with-some-separator-but-without-removing-that-separator-in-j
答案 1 :(得分:2)
如果重复使用regexp这么小的代码,如果重复数千次(例如分析很多文档的Alfresco元数据),就会非常慢。
请看这个片段:
String s = "{key=value}SOMETEXT";
String[] e = null;
long now = 0L;
now = new Date().getTime();
for (int i = 0; i < 3000000; i++) {
e = s.split("(?<=})");
}
System.out.println("Regexp: " + (new Date().getTime() - now));
now = new Date().getTime();
for (int i = 0; i < 3000000; i++) {
int idx = s.indexOf('}') + 1;
e = new String[] { s.substring(0, idx), s.substring(idx) };
}
System.out.println("IndexOf:" + (new Date().getTime() - now));
结果是
Regexp: 2544
IndexOf:113
这意味着regexp比(更简单)子字符串慢25倍。请记住:它可以区分高效代码和优雅(!)之一。
答案 2 :(得分:-2)
如果您正在寻找正则表达式方法并且还希望某些验证输入遵循预期的语法,您可能需要这样的内容:
Here is the code.
$("#fimg").submit(function(e) {
e.preventDefault();
if($("#file").val()!=''){
$.ajax({
url: "<URL TO PHP>",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
//Okay!!
},
error: function()
{
//error.
}
});
}else{
//No Image Selected!
}
});
PHP:
if(isset($_POST['go'])&&$_POST['go']=="Upload"){
//Returns the uploaded path.
}
正则表达式中的括号捕获组,您可以使用public List<String> splitWithRegexp(String string)
{
Matcher matcher = Pattern.compile("(\\{.*\\})(.*)").matcher(string);
if (matcher.find())
return Arrays.asList(matcher.group(1), matcher.group(2));
else
throw new IllegalArgumentException("Input didn't match!");
}
次调用来访问这些组。组matcher.group(n)
匹配整个模式。