我是Java的新手.作为一名.Net开发人员,我非常习惯Regex.Net中的课程.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);
}
Run Code Online (Sandbox Code Playgroud)
在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()));
}
Run Code Online (Sandbox Code Playgroud)
我试图在上面的示例代码中对两种语言都公平.
你在这里注意的第一件事是类的.Value成员Match(与使用.start()和 …
将n个字节的正向lookbehind插入(?<=\C{n})任意正则表达式的开头会有什么后果,特别是在用于替换操作时?
至少在PHP中,正则表达式匹配函数,preg_match并preg_match_all允许匹配在给定的字节偏移之后开始.在任何其他PCRE PHP函数中没有相应的功能 - 例如,您可以指定对替换次数的限制preg_replace,但不能指定那些替换的匹配必须在n个字节之后发生.
显然会有一些(让它们称之为微不足道)对性能和可读性产生影响,但是会有任何(非平凡的)影响,比如匹配变为不匹配(除非它们没有被n个字节偏移)或者替换变得格格不入?
一些例子:
/some expression/成为/(?<=\C{4})some expression/一个4字节的偏移量
/(this) has (groups)/i成为/(?<=\C{2})(this) has (groups)/i2字节的偏移量
据我所知,并且从我运行的有限测试中,添加这个lookbehind有效地模拟了这个偏移参数,并且不会混淆任何其他的lookbehinds,替换或其他控制模式; 但我也不是Regex的专家.
我试图通过将n字节lookbehind插入模式来确定是否有可能对构建替换/过滤器函数扩展产生影响.它应该像匹配函数的偏移参数一样工作 - 因此简单地运行表达式substr( $subject, $offset )将不会出于与其不相同的原因preg_match(最明显的是它会切断任何外观,^然后错误地匹配子字符串的开头,不是原来的字符串).
我试图找到为什么在JAVA中([\ud800-\udbff\udc00-\udfff]) 使用的这个正则表达式replaceAll(regexp,"")也删除了超负字符,以及代理字符.
这个的Unicode是\u002d这样的,它似乎不在任何这些范围内.
我可以轻松删除此行为添加&&[^\u002d]导致([\ud800-\udbff\udc00-\udfff&&[^\u002d]])
但是,由于我不知道为什么\u002d会删除它,我认为可能会有更多未被注意的字符被删除.
例:
String text = "A\u002dB";
System.out.println(text);
String regex = "([\ud800-\udbff\udc00-\udfff])";
System.out.println(text.replaceAll(regex, "X"));
Run Code Online (Sandbox Code Playgroud)
打印:
A-B
AXB
Run Code Online (Sandbox Code Playgroud) 有一个更好的方法吗?
$ python
Python 2.7.9 (default, Jul 16 2015, 14:54:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-55)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.sub(u'[\U0001d300-\U0001d356]', "", "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/fast/services/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/home/fast/services/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: bad character range
Run Code Online (Sandbox Code Playgroud)