我有点想尝试使用正则表达式来分解具有以下属性的字符串:
进行转义
例如,以下是一些我想分解的字符串:
One|Two|Three
应该产生:["One", "Two", "Three"]
One\|Two\|Three
应该产生:["One|Two|Three"]
One\\|Two\|Three
应该产生:["One\", "Two|Three"]
现在我如何用一个正则表达式将其拆分?
更新:正如许多人已经建议的那样,这不是正则表达式的好应用。同样,正则表达式解决方案比仅迭代字符要慢几个数量级。我最终遍历了这些字符:
public static List<String> splitValues(String val) {
final List<String> list = new ArrayList<String>();
boolean esc = false;
final StringBuilder sb = new StringBuilder(1024);
final CharacterIterator it = new StringCharacterIterator(val);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
if(esc) {
sb.append(c);
esc = false;
} else if(c == '\\') {
esc = true;
} else if(c == '|') {
list.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(c);
}
}
if(sb.length() > 0) {
list.add(sb.toString());
}
return list;
}
参考方案
诀窍是不使用split()
方法。这迫使您使用后视来检测转义字符,但是当转义符本身已转义时(如您所知),此操作将失败。您需要改用find()
来匹配标记而不是定界符:
public static List<String> splitIt(String source)
{
Pattern p = Pattern.compile("(?:[^|\\\\]|\\\\.)+");
Matcher m = p.matcher(source);
List<String> result = new ArrayList<String>();
while (m.find())
{
result.add(m.group().replaceAll("\\\\(.)", "$1"));
}
return result;
}
public static void main(String[] args) throws Exception
{
String[] test = { "One|Two|Three",
"One\\|Two\\|Three",
"One\\\\|Two\\|Three",
"One\\\\\\|Two" };
for (String s :test)
{
System.out.printf("%n%s%n%s%n", s, splitIt(s));
}
}
输出:
One|Two|Three
[One, Two, Three]
One\|Two\|Three
[One|Two|Three]
One\\|Two\|Three
[One\, Two|Three]
One\\\|Two
[One\|Two]
Java:找到特定字符并获取子字符串 - java我有一个字符串4.9.14_05_29_16_21,我只需要获取4.9。数字各不相同,所以我不能简单地获得此char数组的前三个元素。我必须找到最正确的.并将其子字符串化直到那里。我来自Python,因此我将展示Python的实现方法。def foobar(some_string): location = some_string.rfind('.&…
Java-搜索字符串数组中的字符串 - java在Java中,我们是否有任何方法可以发现特定字符串是字符串数组的一部分。我可以避免出现一个循环。例如String [] array = {"AA","BB","CC" }; string x = "BB" 我想要一个if (some condition to tell wheth…
在Java中使用新关键字和直接赋值的字符串 - javaString s="hi"; String s1=new String("hi"); 从内存角度看,s和s1存储在哪里?无论是在堆内存还是堆栈中。s指向“ hi”,而s1指向hi存在的内存位置?请帮忙? 参考方案 考虑以下 String s = "hi"; String s1 = new Strin…
Java Regex:将整个单词与单词边界匹配 - java我正在尝试使用Java检查字符串是否整体上包含一个单词。以下是一些示例:Text : "A quick brown fox" Words: "qui" - false "quick" - true "quick brown" - true "ox" - fal…
Java string.hashcode()提供不同的值 - java我已经在这个问题上停留了几个小时。我已经注释掉所有代码,认为这与数组超出范围有关,但是这种情况仍在发生。我正在尝试使用扫描仪从文件中读取输入,存储数据并稍后使用哈希码获取该数据。但是哈希值不断变化。public static void main(String[] args) { //only prior code is to access data char…