将简单的Ruby正则表达式转换为Java

时间:2012-04-18 23:00:16

标签: java ruby regex

在与Ruby合作几年之后,我又回到了Java。我正在寻找能够完成以下Ruby语句的惯用语和短Java代码:

some_string.scan(/[\w|\']+/)

上面的表达式从字符串创建一个数组。数组中的元素是some_string的所有部分,由alphanum chars(\w)或撇号(\'组成,因此“John's”不会分成两个单词。 )

例如:

"(The farmer's daughter) went to the market".scan(/[\w|\']+/)

=>

["The", "farmer's", "daughter", ...]

更新

我知道解决方案会使用类似的东西:

String[] words = sentence.split(" ");

我只需要split()中的正则表达式部分。

3 个答案:

答案 0 :(得分:3)

Java没有内置的scan方法可以在函数调用中执行此操作,因此您需要自己滚动循环。您可以使用Java的正则表达式Matcher类轻松地完成此操作。

import java.util.regex.*;

String yourString = "(The farmer's daughter) went to the supermarket";

/* The regex syntax is basically identical to Ruby, except that you need
 * to specify your regex as a normal string literal, and therefore you need to 
 * double up on your backslashes. The other differences between my regex and 
 * yours are all things that I think you need to change about the Ruby version
 * as well. */
Pattern p = Pattern.compile("[\\w']+");
Matcher m = p.matcher(yourString);
List<String> words = new Vector<String>();
while (m.find()) {
   words.add(m.group());
}

我不确定在这种情况下使用Matcher与使用Scanner的相对优点是什么。

答案 1 :(得分:2)

正则表达式在各种语言中的行为大致相同。在这种情况下,唯一的区别是你必须转义反斜杠和单引号。

如果在Ruby中我们编写/[\w']+/,在Java中我们会写Pattern.compile("[\\w\']+")


哦,Scanners can scan Strings也是如此!

final String s = "The farmer's daughter went to the market";
Scanner sc = new Scanner(s);
Pattern p = Pattern.compile("[\\w\\']+");
while (sc.hasNext(p)) { System.out.println(sc.next(p)); }

这不是完全相同的事情,但为什么不split空格上的字符串,这是字边界?

"The farmer's daughter went to the market".split("\s");

答案 2 :(得分:0)

怎么样

String[] words = test.split("[^a-zA-Z0-9']+");

words = test.split("[^\\w']+");

这些模式与Ruby示例的不同之处在于您使用Ruby的String#scan - 您提供与单词匹配的模式。 Java的String#split就像是Ruby的同名方法 - 你提供了与你的单词分隔符相匹配的模式。

相关问题