猿问

正则表达式否定模式

我在获取这个正则表达式的另一面时遇到了麻烦。

Stranger Number is %19. Friend Number is %30.

我当前的正则表达式是这样(%[0-9]+) 所以当我运行这个正则表达式时。唯一突出显示的是%30%19

Strange Number is %19. Friend Number is %30.

我只是想反过来,%19 和 %30 不是突出显示的,而其他所有内容都突出显示。

我努力了。这个,[^%](?![0-9])但我没有得到我预期的输出。

谢谢您的帮助!


FFIVE
浏览 187回答 2
2回答

偶然的你

为了完整性以及早期版本的 Java,您可以只使用Matcher和while循环来提取与模式匹配的字符串。&nbsp; &nbsp;public static void main( String[] args ) {&nbsp; &nbsp; &nbsp; String test = "Number %1.&nbsp; And number %2 also.";&nbsp; &nbsp; &nbsp; Matcher matcher = Pattern.compile( "%[\\d]+" ).matcher( test );&nbsp; &nbsp; &nbsp; ArrayList<String> results = new ArrayList<>();&nbsp; &nbsp; &nbsp; while( matcher.find() )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;results.add( matcher.group() );&nbsp; &nbsp; &nbsp; System.out.println( results );&nbsp; &nbsp;}

眼眸繁星

根据您想要做什么,您不必为(%[0-9]+).例如,如果您计划提取与反转正则表达式匹配的所有子字符串,则可以使用yourString.split("%[0-9]+").如果您打算%...通过拆分字符串来提取所有内容,则yourString.split(invertedRegex)可以改用匹配器。取自这个答案的代码。String[] matches = Pattern.compile("%[0-9]+").matcher(yourString)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .results().map(MatchResult::group)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray(String[]::new);
随时随地看视频慕课网APP

相关分类

Java
我要回答