如何使用正则表达式提取子字符串 [英] How to extract a substring using regex

查看:21
本文介绍了如何使用正则表达式提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两个单引号的字符串,' 字符.单引号之间是我想要的数据.

如何编写正则表达式从以下文本中提取我想要的数据"?

mydata = "一些字符串,里面有'我想要的数据'";

解决方案

假设您想要单引号之间的部分,请使用带有 Matcher:

"'(.*?)'"

示例:

String mydata = "一些带有'我想要的数据'的字符串";模式 pattern = Pattern.compile("'(.*?)'");匹配器 matcher = pattern.matcher(mydata);如果 (matcher.find()){System.out.println(matcher.group(1));}

结果:

<前>我想要的数据

I have a string that has two single quotes in it, the ' character. In between the single quotes is the data I want.

How can I write a regex to extract "the data i want" from the following text?

mydata = "some string with 'the data i want' inside";

解决方案

Assuming you want the part between single quotes, use this regular expression with a Matcher:

"'(.*?)'"

Example:

String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

Result:

the data i want

这篇关于如何使用正则表达式提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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