捕获字符串上匹配字符(单个或重复)之间的所有字符

时间:2013-06-07 16:26:18

标签: java regex string pattern-matching string-matching

我正在尝试提取特定字符前面的字符串(即使字符重复,就像这样(即:下划线'_'):

this_is_my_example_line_0
this_is_my_example_line_1_
this_is_my_example_line_2___
_this_is_my_ _example_line_3_
__this_is_my___example_line_4__

运行我的正则表达式之后我应该得到这个(正则表达式应该忽略字符串中间匹配字符的任何实例):

this_is_my_example_line_0
this_is_my_example_line_1
this_is_my_example_line_2
this_is_my_ _example_line_3
this_is_my___example_line_4

换句话说,我正试图在字符串的开头和结尾处“修剪”匹配的字符。

我正在尝试使用Java中的Regex来实现这一点,我的想法是捕获行末或行首的特殊字符之间的字符组。

到目前为止,我只能通过此正则表达式成功执行此示例3:

/[^_]+|_+(.*)[_$]+|_$+/

[^_]+ not 'underscore' once or more 
| OR 
_+ underscore once or more
(.*) capture all characters
[_$]+ not 'underscore' once or more followed by end of line
 |_$+ OR 'underscore' once or more followed by end of line

我刚刚意识到这排除了示例0,1,2上消息的第一个字,因为字符串不是以下划线开头的,而是在找到下划线后才开始匹配..

是否有更简单的方法不涉及正则表达式? 我真的不关心第一个角色(虽然它会很好)我​​只需要忽略最后的重复角色..它看起来(by this regex tester)只是这样做,会起作用吗? /()_+$/空括号在单行之前匹配任何内容或在行尾重复匹配..这是正确的吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

这里有几个选项,你可以用空字符串替换^_+|_+$的匹配,或者从^_*(.*?)_*$的匹配中提取第一个捕获组的内容。请注意,如果您的字符串可能是多行,并且您希望在每行上执行替换,那么您将需要使用Pattern.MULTILINE标志进行任一种方法。如果您的字符串可能是多行,并且您只想在开头和结尾进行替换,请不要使用Pattern.MULTILINE,而是使用Pattern.DOTALL进行第二种方法。

例如:http://regexr.com?355ff

答案 1 :(得分:2)

[^_\n\r](.*[^_\n\r])?怎么样?

演示

String data=
        "this_is_my_example_line_0\n" +
        "this_is_my_example_line_1_\n" +
        "this_is_my_example_line_2___\n" +
        "_this_is_my_ _example_line_3_\n" +
        "__this_is_my___example_line_4__";

Pattern p=Pattern.compile("[^_\n\r](.*[^_\n\r])?");
Matcher m=p.matcher(data);
while(m.find()){
    System.out.println(m.group());
}

输出:

this_is_my_example_line_0
this_is_my_example_line_1
this_is_my_example_line_2
this_is_my_ _example_line_3
this_is_my___example_line_4