saa*_*adi 6 regex string scala
我有一个大字符串,我想[[someword]]
从中获取格式的所有子字符串。
意思是,获取包含在左右方括号中的所有单词(列表)。
现在,一种方法是按空格分割字符串,然后使用此过滤器过滤列表,但问题是有时[[someword]]
不作为单词存在,它可能有一个,
, 空格或.
在其之前或之后。
做这个的最好方式是什么?
我会很欣赏 Scala 中的解决方案,但由于这更多的是一个编程问题,如果您的解决方案是我知道的其他语言(例如 Python),我会将其转换为 Scala。
这个问题与标记重复问题不同,因为正则表达式需要能够在括号之间容纳英语字符以外的字符。
您可以使用此(?<=\[{2})[^[\]]+(?=\]{2})
正则表达式来匹配和提取双方括号中包含的所有所需单词。
这是一个Python解决方案,
import re
s = 'some text [[someword]] some [[some other word]]other text '
print(re.findall(r'(?<=\[{2})[^[\]]+(?=\]{2})', s))
Run Code Online (Sandbox Code Playgroud)
印刷,
['someword', 'some other word']
Run Code Online (Sandbox Code Playgroud)
我从未在 Scala 中工作过,但这里有一个 Java 解决方案,据我所知 Scala 仅基于 Java,因此这可能会有所帮助。
String s = "some text [[someword]] some [[some other word]]other text ";
Pattern p = Pattern.compile("(?<=\\[{2})[^\\[\\]]+(?=\\]{2})");
Matcher m = p.matcher(s);
while(m.find()) {
System.out.println(m.group());
}
Run Code Online (Sandbox Code Playgroud)
印刷,
someword
some other word
Run Code Online (Sandbox Code Playgroud)
让我知道这是否是您正在寻找的。
归档时间: |
|
查看次数: |
862 次 |
最近记录: |