使用正则表达式从Java中的引号中提取两个字符串?
我是使用模式的新手,并在互联网上到处寻找对此问题的解释。
假设我有一个字符串: String info = "Data I need to extract is 'here' and 'also here'";
我将如何提取单词:
here
also here
不使用模式的单引号?
这就是我到目前为止所拥有的......
Pattern p = Pattern.compile("(?<=\').*(?=\')");
但它返回( here 和 'also here
)减去括号,这只是为了查看。它会跳过第二条数据并直接转到最后一个引用...
谢谢!
编辑:
谢谢大家的回复!如何更改模式,以便这里存储在matcher.group(1)中,而也在这里存储在matcher.group(2)中?我出于不同的原因需要这些值,将它们从一组中拆分似乎效率很低......
I'm new to using patterns and looked everywhere on the internet for an explanation to this problem.
Say I have a string: String info = "Data I need to extract is 'here' and 'also here'";
How would I extract the words:
here
also here
without the single quotes using a pattern?
This is what I have so far...
Pattern p = Pattern.compile("(?<=\').*(?=\')");
But it returns ( here and 'also here
) minus the brackets, that is just for viewing. It skips over the second piece of data and goes straight to the last quote...
Thank you!
EDIT:
Thank you for your replies everyone! How would it be possible to alter the pattern so that here is stored in matcher.group(1) and also here is stored in matcher.group(2)? I need these values for different reasons, and splitting them from 1 group seems inefficient...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使您的正则表达式非贪婪:
编辑:
这不起作用。它给出以下匹配:
这是因为前向/后向不消耗
'
。要解决此问题,请使用正则表达式:
或者甚至更好(更快):
Try making your regex non-greedy:
EDIT:
This does not work. It gives the following matches:
This is because the lookahead/lookbehind do not consume the
'
.To fix this use the regex:
or even better (& faster):
我认为你把它弄得很复杂,尝试一下
,否则
它们都会起作用。然后,您可以在执行
matcher.find()
后从第一组matcher.group(1)
中提取结果。I think you're making it to complicated, try
or
They will both work. Then you can extract the result from the first group
matcher.group(1)
after performing amatcher.find()
.这应该对您有用:
这是打印输出:-
如果您想要将数据分为 2 个单独的组,您可以执行以下操作:-
这是打印输出:
This should work for you:
Here's the printout:-
If you want the data in 2 separate groups, you could do something like this:-
Here's the printout:
为什么不简单地使用以下内容?
Why not using simply the following?