我有一个跟随字符串,我想要解析为List或String []。
(Test)(Testing (Value))
最终结果应为Test
和Testing (Value)
答案 0 :(得分:2)
如果我理解你需要Test
和Testing (Value)
,那么这里是regexp:
\(([^\)]+)\)\((.+)\)
并且它的掩码版本已准备好用于java字符串:
\\(([^\\)]+)\\)\\((.+)\\)
答案 1 :(得分:0)
请阅读php手册的this部分。它告诉您递归模式,它可以用来匹配嵌套的东西,以及相关的问题。谷歌了解更多信息。
答案 2 :(得分:0)
这个问题真的很模糊,但根据一个合理的解释,这个解决方案可以处理某种格式的任意嵌套深度:
String text = "(T)(T(V))(1(2(3)2)1)(a*(b+(c-d))+(e/f))";
String[] parts = text.split("(?<=\\))(?=\\()");
System.out.println(java.util.Arrays.toString(parts));
// prints "[(T), (T(V)), (1(2(3)2)1), (a*(b+(c-d))+(e/f))]"
基本上你想在split
之间)(
(使用断言)。不适用于所有情况,例如((.)(.))
,但正如许多人所说,问题的要求是模糊的,并且Java正则表达式无法解决一般平衡括号问题。
答案 3 :(得分:-1)
/**
* Parse string:
* when '$' symbol is encountered it deletes it's previous character and the '$' symbol itself
* when '@' symbol is encountered it erases the text previous to it and the '@' symbol itself
* @author Rama Bolishetty
* @date Feb 27, 2016
*/
package com.ram.utilities;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseString {
private static final Pattern dollarSymborPattern = Pattern.compile("[a-zA-Z0-9]{0,1}[$]{1}");
private static final Pattern atSymbolPattern = Pattern.compile("[a-zA-Z0-9$]{0,}[@]{1}");
public static String parseString(String inputString) {
String parsedString = inputString;
Matcher m = atSymbolPattern.matcher(parsedString);
String matcher = replaceMatcher(m);
parsedString = matcher != null ? matcher : parsedString;
m = dollarSymborPattern.matcher(parsedString);
parsedString = replaceMatcher(m);
parsedString = matcher != null ? matcher : parsedString;
return parsedString;
}
private static String replaceMatcher(Matcher m) {
if (m.find()) {
return m.replaceAll("");
}
return null;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String inputString = scanner.nextLine();
long sTime, eTime;
System.out.println("STime:" + (sTime = System.currentTimeMillis()) + "\nParsed String:"
+ ParseString.parseString(inputString) + "ETime:" + (eTime = System.currentTimeMillis()));
System.out.println("Total milliseconds:" + (eTime - sTime));
scanner.close();
}
}