如何获取字符串中的所有内容,但特定模式除外
另一个正则表达式问题:
我有一个字符串,如下所示,
“这是一个字符串,我有优先权!1”
所以我想构建一个正则表达式来提取我的优先级,即前面带有“!”的数字 1。 提取它非常简单,“!([1-4])”。但现在我想提取文本,将其保留!我怎样才能做到这一点?
DETAIL:!1 可以位于字符串中的任何位置,因此这也完全可以:
“这是一个字符串,!1,我有优先权” 谢谢
!
更新:我正在使用 scala
Yet another regexp question:
I have a string as the following,
"This is a string, and I have a priority !1"
So I want to build a regexp that extracts my priority, which is this number 1 preceded by the "!".
To extract it is very easy, "!([1-4])". But now I want to extract the text, leaving it out! How can I do that?
DETAIL: The !1 can be anywhere in the string, so this is also perfectly fine:
"This is a string, !1 and I have a priority"
Thanks!
UPDATE: I'm using scala
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 !1、!2、!3 和 !4 替换为空字符串:
String newString = "some string with !1 and more text".replaceAll("![1-4]", "") ;
You can replace !1, !2, !3 and !4 with the empty string:
String newString = "some string with !1 and more text".replaceAll("![1-4]", "");
此正则表达式使用 惰性量词 以获得更好的性能,并将为您提供三个捕获组:
您还可以使用类似 String.replace() 或 Matcher.appendReplacement() 正如 jarnbjo 在他的回答中提到的,但无论如何,这三组都能满足您的需求。
编辑:这是正则表达式的正确版本:
根据评论,我将第二个量词设置为贪婪,以便它与字符串的其余部分匹配。
This regex uses lazy quantifiers for better performance and will give you three capture groups:
You can also use something like String.replace() or Matcher.appendReplacement() as jarnbjo mentions in his answer, but in any case, these three groups give you what you need.
EDIT: Here is a correct version of the regex:
Based on the comments, I made the second quantifier greedy so it matches the rest of the string.