gpt4 book ai didi

Java:正则表达式 - 我如何获得第一个引号文本

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:32 24 4
gpt4 key购买 nike

作为 regex 的初学者,我想我会问一些太简单的问题,但我还是会问,希望它不会打扰你帮助我..

假设我有一个像“你好'cool1'字!'cool2'”这样的文本我想获取第一个引号的文本(即没有 ' 的 'cool1')

我的模式应该是什么?在使用匹配器时,我如何保证它将保留在第一个引号而不是第二个引号中?

(请建议仅使用正则表达式的解决方案..)

最佳答案

使用这个正则表达式:

'([^']*)'

Use as follows: (ideone)

Pattern pattern = Pattern.compile("'([^']*)'");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}

或者,如果您知道引用的字符串中没有换行符:

'(.*?)'

when using matcher, how do i guarantee it will remain the first quote and not the second?

它会首先找到第一个引用的字符串,因为它是从左到右开始搜索的。如果你要求它进行下一场比赛,它会给你第二个带引号的字符串。

关于Java:正则表达式 - 我如何获得第一个引号文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10769813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com