2012-04-18 23 views
0

我在用Ruby數年的間隙後返回Java。我正在尋找的是完成以下Ruby代碼習慣和短Java代碼:將簡單的Ruby正則表達式轉換爲Java

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

上述表達式創建一個字符串數組。陣列中的元素是由任一alphanum字符(\w)或撇號的的some_string所有部分

例如(\'使「約翰的」不分成兩個單詞。):

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

=>

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

更新

我知道該解決方案將使用這樣的事情:

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

我只需要一個進去split()正則表達式的一部分。

+0

我知道java和java中的正則表達式 - 但我不明白你在做什麼Ruby正則表達式。你能用言語說出來嗎? :) – Mads 2012-04-18 23:07:45

+0

我澄清了上面的正則表達式。 – bevanb 2012-04-18 23:15:42

+0

你不需要'|'在一個字符類中(括號括起來[]'),並且你不需要轉義'''。正則表達式'/ [\ w'] + /'是正確的,而你的是錯誤的。 – 2012-04-19 01:02:25

回答

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這種情況。

+0

感謝您的修復。只是做了一個小小的改變,它工作。 – bevanb 2012-04-19 13:55:09

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"); 
+0

非常接近。我知道我需要使用.split,我只需要正則表達式來過濾非撇號字符,除了撇號。 – bevanb 2012-04-18 23:22:48

+0

@bevanb,我剛剛瞭解到['Scanner's](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)也適用於'String's。看看它是否能解決你的問題。而且,方括號內的'|'是不必要的。 – 2012-04-18 23:38:06

+2

Ruby中的正則表達式應該是'/ [\ w'] + /',而Java中的等價正則表達式是''[\\ w'] +「'。 – 2012-04-19 01:05:56

0

如何

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

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

從你的Ruby例如,這些模式所不同的是,因爲你使用Ruby的字符串#掃描 - 在您提供的匹配模式一個字。 Java的String#split就像Ruby的同名方法 - 你提供的模式匹配你的單詞分隔符。

相關問題