fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.regex.*;
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. String str = "HELLO_WORLD_123456 TEst";
  13.  
  14. System.out.println ("First test");
  15. String regex1 = ".*(WORLD).*";
  16. String matchedString = getValueByregexExpr (str, regex1);
  17. //Here, I want to obtain matchedString = WORLD
  18. if (matchedString == null) {
  19. System.out.println ("matchedString null");
  20. } else if (matchedString.equals (regex1)) {
  21. System.out.println ("String found but empty group(1)");
  22. } else {
  23. System.out.println ("Result : " + matchedString);
  24. }
  25.  
  26. //Here, I want to obtain matchedString = WORLD_123456
  27. System.out.println ("\nSecond test");
  28. String regex2 = "(WORLD_[^_\\s]+)";
  29. matchedString = getValueByregexExpr (str, regex2);
  30. if (matchedString == null) {
  31. System.out.println ("regex " + regex2 + " matchedString null");
  32. } else if (matchedString == regex2) {
  33. System.out.println ("regex " + regex2 + " String found but empty group(1)");
  34. } else {
  35. System.out.println ("regex " + regex2 + " Result : " + matchedString);
  36. }
  37.  
  38. }
  39. public static String getValueByregexExpr (String str, String regexExpr)
  40. {
  41. Pattern regex = Pattern.compile (regexExpr, Pattern.DOTALL);
  42. Matcher matcher1 = regex.matcher (str);
  43. if (matcher1.find ()) {
  44. if (matcher1.groupCount () != 0 && matcher1.group (1) != null) {
  45. for (int i = 0; i <= matcher1.groupCount (); i++) {
  46. System.out.println ("matcher " + i + " for regex " + regexExpr + "= " + matcher1.group (i));
  47. }
  48. return matcher1.group (1);
  49. }
  50. return regexExpr;
  51. }
  52. return null;
  53. }
  54. }
Success #stdin #stdout 0.09s 320576KB
stdin
Standard input is empty
stdout
First test
matcher 0 for regex .*(WORLD).*= HELLO_WORLD_123456 TEst
matcher 1 for regex .*(WORLD).*= WORLD
Result : WORLD

Second test
matcher 0 for regex (WORLD_[^_\s]+)= WORLD_123456
matcher 1 for regex (WORLD_[^_\s]+)= WORLD_123456
regex (WORLD_[^_\s]+) Result : WORLD_123456