在Java中使用正则表达式匹配后删除部分字符串 [英] Remove part of String following regex match in Java

查看:737
本文介绍了在Java中使用正则表达式匹配后删除部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除与正则表达式匹配的字符串的一部分。

I want to remove a part of a string following what matches my regex.

我正在尝试制作一个电视节目组织节目,我希望在SXXEXX形式的季节和剧集标记之后切断名称中的任何内容,其中X是一个数字。

I am trying to make a TV show organization program and I want to cut off anything in the name following the season and episode marker in the form SXXEXX where X is a digit.

我很容易掌握正则表达式模型来创建[Ss] \d\d [Ee] \\\这应该匹配正确。

I grasped the regex model fairly easily to create "[Ss]\d\d[Ee]\d\d" which should match properly.

我想使用Matcher方法end()来获取匹配字符串中的最后一个索引,但它似乎没有像我认为的那样工作。

I want to use the Matcher method end() to get the last index in the string of the match but it does not seem to be working as I think it should.

Pattern p = Pattern.compile("[Ss]\\d\\d[Ee]\\d\\d");
Matcher m = p.matcher(name);

if(m.matches())
    return name.substring(0, m.end());

如果有人能告诉我为什么这不起作用并提出正确的方法,那就是会很好。谢谢。

If someone could tell me why this doesn't work and suggest a proper way to do it, that would be great. Thanks.

推荐答案

matches()尝试再次匹配整个字符串模式。如果要在字符串中查找模式,请使用 find() find()将搜索下一个匹配字符串。

matches() tries to match the whole string again the pattern. If you want to find your pattern within a string, use find(), find() will search for the next match in the string.

您的代码可能完全相同:

Your code could be quite the same:

if(m.find())
    return name.substring(0, m.end());

这篇关于在Java中使用正则表达式匹配后删除部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆