我正在尝试提取特定字符之前的字符串(即使在重复字符时也是如此(例如:下划线'_'):
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__在运行regex之后,我应该得到它( regex应该忽略字符串中间匹配字符的任何实例):
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来实现这一点,我的想法是在行尾或行首捕获特殊字符之间的一组字符。
到目前为止,我只能用这个regexp成功地完成这个操作,例如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上消息的第一个单词,因为字符串不以下划线开头,只有在找到下划线后才开始匹配。
有没有更简单的方法不涉及regex?我真的不关心第一个字符(虽然这会很好),我只需要忽略结尾的重复字符。看起来(通过这个regex测试器)就是这么做的,会起作用吗?/()_+$/空括号匹配单行之前的任何内容,或者在行尾重复匹配。那是对的吗?
谢谢!
发布于 2013-06-07 16:37:32
这里有几个选项,您可以用空字符串替换^_+|_+$的匹配,或者从^_*(.*?)_*$的匹配中提取第一个捕获组的内容。请注意,如果您的字符串可能是多行,并且您希望在每一行上执行替换,那么您将需要为这两种方法使用Pattern.MULTILINE标志。如果您的字符串可能是多行,并且只希望在开始和结束时替换,则不要使用Pattern.MULTILINE,而是在第二种方法中使用Pattern.DOTALL。
例如:http://regexr.com?355ff
发布于 2013-06-07 16:37:59
[^_\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_4https://stackoverflow.com/questions/16988829
复制相似问题