【问题标题】:capture all characters between match character (single or repeated) on string捕获字符串上匹配字符(单个或重复)之间的所有字符
【发布时间】:2013-06-04 00:57:16
【问题描述】:

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

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)只是这样做,会工作吗? /()_+$/ 空括号匹配行尾的单个或重复匹配之前的任何内容.. 正确吗?

谢谢!

【问题讨论】:

  • 澄清一下,您是否要删除字符串开头和结尾的所有下划线?

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


【解决方案1】:

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

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

【讨论】:

  • 哦,使正则表达式 ^~*(.*?)~*$ 起作用的关键是中间的惰性匹配!所以正则表达式的结尾部分 ~*$ 将能够捕获其余部分! :)
【解决方案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

【讨论】:

  • 您在使用 Java 吗?毫米我想知道我一直在尝试的正则表达式测试器是否不正确......因为根据gskinner.com/RegExr,您的正则表达式省略了每个句子的第一个字符
  • 哦,它匹配得很好,但是他们显示的组不正确.. 我认为他们错了regexr.com?355fi
  • @david 如果您想将整个比赛放在第一组中,您需要用括号将正则表达式括起来,例如([^_\n\r](.*[^_\n\r])?)。在 Java 中,您可以使用组 0 进行整个匹配。
  • @david 据我所知,如果你想在gskinner.com/RegExr 使用整个匹配,那么你需要使用$& 而不是$1
猜你喜欢
  • 2018-07-28
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 2013-12-28
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
相关资源
最近更新 更多