Redian新闻
>
How to get a matched String?
avatar
How to get a matched String?# Java - 爪哇娇娃
g*g
1
If you have a long text, you want to use regex to match it and
get back the first matched String, is this what I should do?
String[] strs = text.split("regex", 2);
text.substring(strs[0].length, text.length - strs[1].length);
avatar
t*e
2
try Pattern and Matcher classes.
avatar
m*t
3

But that only gets you the part _before_ the first matching substring.
Try something like Pattern.compile(regex).matcher(text).find()

【在 g*****g 的大作中提到】
: If you have a long text, you want to use regex to match it and
: get back the first matched String, is this what I should do?
: String[] strs = text.split("regex", 2);
: text.substring(strs[0].length, text.length - strs[1].length);

avatar
g*g
4
Actually this should work, coz str[0] is the part before, and
str[1] is the part after. But your way looks more elegant.

【在 m******t 的大作中提到】
:
: But that only gets you the part _before_ the first matching substring.
: Try something like Pattern.compile(regex).matcher(text).find()

avatar
m*t
5

Oh, right, now that I read it again, the index jumping makes
sense.
...Yeah... I guess that shows the pattern approach _is_ at least
more readable. ;-)

【在 g*****g 的大作中提到】
: Actually this should work, coz str[0] is the part before, and
: str[1] is the part after. But your way looks more elegant.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。