我是Java的新手。作为.Net开发人员,我非常习惯.Net中的Regex
类。 Regex
(正则表达式)的Java实现并不错,但缺少一些关键功能。
我想为Java创建自己的帮助器类,但我想也许已经有一个可用的了。那么有什么免费且易于使用的产品可用于Java中的Regex,还是我应该自己创建一个?
如果我要写自己的课程,你认为我应该把它分享给其他人使用它?
[编辑]
有人抱怨说我没有解决当前Regex
课程的问题。我会试着澄清我的问题。
在.Net中,正则表达式的使用比Java更容易。由于这两种语言都是面向对象的,并且在很多方面非常相似,我希望在两种语言中使用正则表达式都有类似的经验。不幸的是,事实并非如此。
这是Java和C#中的一些代码。第一个是C#,第二个是Java:
在C#中:
string source = "The colour of my bag matches the color of my shirt!";
string pattern = "colou?r";
foreach(Match match in Regex.Matches(source, pattern))
{
Console.WriteLine(match.Value);
}
在Java中:
String source = "The colour of my bag matches the color of my shirt!";
String pattern = "colou?r";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(source);
while(m.find())
{
System.out.println(source.substring(m.start(), m.end()));
}
我试图在上面的示例代码中对两种语言都公平。
您在这里注意的第一件事是.Value
类的Match
成员(与在Java中使用.start()
和.end()
相比)。
当我可以调用Regex.Matches
或Regex.Match
之类的静态函数时,为什么要创建两个对象?
在更高级的用法中,差异显示出更多。查看方法Groups
,字典长度,Capture
,Index
,Length
,Success
等。这些都是非常必要的功能,在我看来应该是也可用于Java。
当然,所有这些功能都可以通过自定义代理(帮助程序)类手动添加。这是我问这个问题的主要原因。我们在Perl中没有Regex
的微风,但至少我们可以使用.Net方法Regex
,我认为这是非常巧妙的设计。
答案 0 :(得分:108)
答案 1 :(得分:9)
一个人可以咆哮,或者可以简单地写:
public class Regex {
/**
* @param source
* the string to scan
* @param pattern
* the regular expression to scan for
* @return the matched
*/
public static Iterable<String> matches(final String source, final String pattern) {
final Pattern p = Pattern.compile(pattern);
final Matcher m = p.matcher(source);
return new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
@Override
public boolean hasNext() {
return m.find();
}
@Override
public String next() {
return source.substring(m.start(), m.end());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
}
按照您的意愿使用:
public class RegexTest {
@Test
public void test() {
String source = "The colour of my bag matches the color of my shirt!";
String pattern = "colou?r";
for (String match : Regex.matches(source, pattern)) {
System.out.println(match);
}
}
}
答案 2 :(得分:2)
@ tchrist的答案中提到的一些API缺陷已在Kotlin中修复。
答案 3 :(得分:1)
男孩,我是否听说过那个Alireza!正则表达式是令人困惑的,没有这么多的语法变化。我也做了比Java编程更多的C#并遇到了同样的问题。
我发现这非常有帮助: http://www.tusker.org/regex/regex_benchmark.html - 它是Java的替代正则表达式实现列表,已经过基准测试。
答案 4 :(得分:0)
如果我自己说的话,这真是太好了! regex-tester-tool