2013-10-16 134 views
1

这似乎是一个基本的东西,但我似乎无法绕过正则表达式的我从来没有真正使用过它们,现在我遇到了一段时间,他们会有用。Java使用和分割字符串使用正则表达式

我看过过去一个小时的例子和过去的问题,但仍然不明白。我的问题是我有一个字符串

"(2 h 9 min from now) | +18.7 feet" 

,我想分成两个字符串

String a = "2 h 9 min from now"; 

String b = "18.7 feet"; 

我如何使用正则表达式,并使用分割字符串的“正则表达式的'在其他字符串?

到目前为止,我想出了:

stringx.split("(%s) | +%s \n"); 

stringx.split("(\\w) | +\d.\d feet"); 

但我不知道怎么弄%S(如果多数民众赞成甚至右)到正则表达式

之外的字符串
+0

你似乎混淆了'分裂'与正则表达式模式匹配。 –

回答

2

当你想删除一些字符(在()+),最安全的方法是PatternMatcher类标准的正则表达式匹配:

public static void main (String[] args) { 
    String input= "(2 h 9 min from now) | +18.7 feet"; 
    System.out.println("Input: "+ input); 
    Pattern p = Pattern.compile("\\(([^)]+)\\) \\| \\+(\\d+\\.\\d feet)"); 
    Matcher m = p.matcher(input); 
    String a = null, b = null; 
    if (m.find()) { 
     a = m.group(1); 
     b = m.group(2); 
    } 
    System.out.println("a: "+ a); 
    System.out.println("b: "+ b); 
} 

输出:

Input: (2 h 9 min from now) | +18.7 feet 
a: 2 h 9 min from now 
b: 18.7 feet 

See online demo here

+0

**注意:**如果您确实想使用String#split(),您可以使用** [此演示中的代码](http://ideone.com/fSit7Y)**。虽然我不会推荐它,因为输入中的细微变化可能会导致意想不到的输出,并且您的意图在代码中不明确(如果维护它的人 - 可能是您自己的将来 - 会更难) 。 – acdcjunior

+0

它仍然看起来很乱,使用正则表达式。它是从api api的bufferedReader中获取的一段信息。免除字符串。替换字符串.split你会推荐我使用什么?编辑 - 是的,我知道strickly我应该使用一个XML解析器,但我不能让一个正常工作,并看到我可以在20行(解析器60行以下)做同样的事情我想探索使其更多高效并进一步压缩 – Greg

+0

我仍然建议使用正则表达式(和模式/匹配器类)。我知道它看起来有点乱,但是你的场景真的是正则表达式的用例。其他方法,比如'split()'或'replace()',可能会发送错误的消息(它们会使代码更难读)。尽管如此,使用正则表达式,您可以使用方法使代码更简单。例如,** [检查此演示](http://ideone.com/4yjO3Z)**。国际海事组织,它非常干净。 – acdcjunior

0

您可以使用:

String s = "(2 h 9 min from now) | +18.7 feet"; 
Pattern p = Pattern.compile("^\\(([^)]+)\\)\\s*\\|\\s*\\+(.*)$"); 
Matcher m = p.matcher(s); 
if (m.find())    
    System.out.println(m.group(1) + " :: " + m.group(2)); 

// 2 h 9 min from now :: 18.7 feet 
+0

OP想要摆脱括号和加号。 –

+0

@BoristheSpider:我刚刚注意到,让我编辑。 – anubhava

0
StringTokenizer stringtokenizer = new StringTokenizer("Your string", "|"); 
while (stringtokenizer.hasMoreElements()) { 
System.out.println(stringtokenizer.nextToken()); 
} 
0

我会这样做的两个步骤。

  • 首先,拆分
  • 然后,消毒

例如:

// the original text 
String text = "(2 h 9 min from now) | +18.7 feet"; 
// splitting on the "|" separator 
String[] splitted = text.split("\\|"); 
// printing the raw "split" array 
System.out.println("Raw: " + Arrays.toString(splitted)); 
// iterating over the raw elements of the array 
for (String split: splitted) { 
    // replacing all "raw" strings with the group composed of 
    // word characters in between non word characters (if any) 
    System.out.println(split.replaceAll("^\\W*(.+?)\\W*$", "$1")); 
} 

输出:

Raw: [(2 h 9 min from now) , +18.7 feet] 
2 h 9 min from now 
18.7 feet 

不是干净的解决方案,但它”我会给你一个开始。

相关问题