[英]Parsing String with Regex in Java
I have a String which is formatted as such 我有一个这样格式化的字符串
[dgdds,dfse][fsefsf,sefs][fsfs,fsef]
How would I use Regex to quickly parse this to return an ArrayList with each value containing one "entry" as such? 我将如何使用Regex快速解析此内容以返回一个ArrayList,每个值都包含一个这样的“ entry”?
ArrayList <String>:
0(String): [dgdds,dfse]
1(String): [fsefsf,sefs]
2(String): [fsfs,fsef]
Really stuck with this, any help would be great. 真正坚持这一点,任何帮助都将是巨大的。
How about 怎么样
String myData = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
List<String> list = new ArrayList<>(Arrays.asList(myData
.split("(?<=\\])")));
for (String s : list)
System.out.println(s);
Output: 输出:
[dgdds,dfse]
[fsefsf,sefs]
[fsfs,fsef]
This regex will use look behind mechanism to split on each place after ]
. 该正则表达式将使用后向机制在]
之后在每个位置上拆分。
You should try this regex : 您应该尝试此正则表达式:
Pattern pattern = Pattern.compile("\\\\[\\\\w*,\\\\w*\\\\]"); 模式模式= Pattern.compile(“ \\\\ [\\\\ w *,\\\\ w * \\\\]”);
Old, easy, awesome way :) 旧的,简单的,很棒的方法:)
String s = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
String[] token = s.split("]");
for (String string : token) {
System.out.println(string + "]");
}
You may need to do it in two passes: 您可能需要两遍操作:
(1) Split out by the brackets if it's just a 1D array (not clear in the question): (1)如果只是一维数组,则用方括号将其分开(问题中不清楚):
String s = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
String[] sArray = s.split("\\[|\\]\\[|\\]");
(2) Split by the commas if you want to also divide, say "dgdds,dfse" (2)如果要除以逗号 ,请说“ dgdds,dfse”
sArray[i].split(",");
You can use simple \\[.*?\\]
regex, which means: match a string starting with [
, later zero or more characters (but as short as possible, not greedly, that's why the ?
in .*?
), ending with ]
. 您可以使用简单的\\[.*?\\]
正则表达式,这意味着:匹配字符串开始[
,后来零个或多个字符(但尽可能短,不greedly,这就是为什么?
在.*?
以结束]
。
This works, you can test it on Ideone : 这有效,您可以在Ideone上对其进行测试:
List<String> result = new ArrayList<String>();
String input = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
Pattern pattern = Pattern.compile("\\[.*?\\]");
Matcher matcher = pattern.matcher(input);
while (matcher.find())
{
result.add(matcher.group());
}
System.out.println(result);
Output: 输出:
[[dgdds,dfse], [fsefsf,sefs], [fsfs,fsef]]
We can use split(regex)
function directly by escaping "]"
: "\\\\]"
and then use it as the regex
for pattern matching: 我们可以通过转义"]"
: "\\\\]"
直接使用split(regex)
函数,然后将其用作模式匹配的regex
:
String str = "[dgdds,dfse][fsefsf,sefs][fsfs,fsef]";
String bal[] = str.split("\\]");
ArrayList<String>finalList = new ArrayList<>();
for(String s:bal)
{
finalList.add(s+"]");
}
System.out.println(finalList);
如果][
之间没有任何内容,则使用此(?:(?<=\\])|^)(?=\\[)
拆分可能有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.