1

I'm having trouble getting the other side of this regex.

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

My current regex is this (%[0-9]+) So when I run this regex. The only highlighted are the %30 and %19.

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

I just want it the other way around where %19 and %30 is not the highlighted one and everything else is highlighted.

I have tried. this one [^%](?![0-9]) but im not getting my expected output.

thanks for the help!

Dranym
  • 13
  • 4

2 Answers2

1

Depending you what you want to do, you don't have to find an inverted regex for (%[0-9]+).

For instance, if you planned to extract all substrings matching the inverted regex, you could use yourString.split("%[0-9]+").

If you planned to extract all the %... by splitting the string with yourString.split(invertedRegex) you could use a matcher instead.
Code taken from this answer.

String[] matches = Pattern.compile("%[0-9]+").matcher(yourString)
                          .results().map(MatchResult::group)
                          .toArray(String[]::new);
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • I think this is the one. Let me try it. – Dranym Nov 06 '18 at 20:19
  • Don't forget the `import java.util.regex.Pattern;` and `import java.util.regex.MatchResult;`. – Socowi Nov 06 '18 at 20:20
  • This should work but im not yet on Java 9. :( Im using the one above :) Can I make 2 solutions correct? lol – Dranym Nov 06 '18 at 20:29
  • @Dranym Thank you for your reply. You can only accept one answer. But when you have (I think) 15 points you can upvote the other answer. By the way, java 8 should be sufficient. – Socowi Nov 06 '18 at 20:31
  • I have upvoted this answer but the system says my vote wont get publicized unless i reached 15 points. – Dranym Nov 06 '18 at 20:33
1

For completeness, and those on earlier versions of Java, you can just use the Matcher and a while loop to extract strings that match a pattern.

   public static void main( String[] args ) {
      String test = "Number %1.  And number %2 also.";
      Matcher matcher = Pattern.compile( "%[\\d]+" ).matcher( test );
      ArrayList<String> results = new ArrayList<>();
      while( matcher.find() )
         results.add( matcher.group() );
      System.out.println( results );
   }
markspace
  • 10,621
  • 3
  • 25
  • 39