我想要得到“get-this
”,周围没有空格。
String input = "adfa dfadf[somestring] get-this adfaf adfadfad adfajiojoij [somestring] dont-get-this ";
所以基本上我想在first配对方括号之后获得first字符串。 这是我的正则表达式,但它不起作用:
(?<=.*?\[.*?\]\p{Blank}).*?[\]^.*?\p{Blank}]
但是如果我改变“.*?”在方括号之间插入“somestring”它可以工作。
有人知道为什么吗?任何帮助将不胜感激!
提前致谢。
最佳答案
首先,您不能在 Java 的后向断言中使用像 *
或 *?
这样的量词。在lookbehind中只允许使用有限的量词{m,n}
,因此你可以用这种方式编写你的模式:
(?<=\[[^]]{1,1000}]\s{0,1000})\S+
或者在java字符串中:
string pattern = "(?<=\\[[^]]{1,1000}]\\s{0,1000})\\S+";
图案详细信息:
(?<= # open the lookbehind: preceded by...
\[ # a literal [
[^]]{1,1000} # between one and 1000 characters that are not a ]
] # literal ]
\s{0,1000} # between zero and 1000 white-spaces
) # close the lookbehind
\S+ # one or more characters that are not white-spaces
请注意,lookbehind 只是一个测试,里面描述的所有内容不会包含在整个比赛结果中。
根据您想要执行的操作,可能根本不需要向后查找,并且您可以简单地使用捕获组来获得相同的结果:
\[[^]]+]\s*(\S+)
图案详细信息:
\[ # a literal [
[^]]+ # one or more characters that are not a ]
] # a literal ]
\s* # zero or more white-spaces
( # open the capture group 1
\S+ # all that is not a white-space
) # close the capture group 1
当此模式成功时,将返回两个结果:整个匹配(与之前的模式相同)和捕获组 1(括号内的部分)。捕获组是提取较大模式的特定部分的便捷方法。 那么你只需要提取捕获组1即可得到你想要的。
关于java - 在Java中使用正则表达式获取 "get this"中的字符串 "adfadf[somestring] get-this adfaf",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31127085/