-3

There are some perl regular expressions that I need to convert to Java regular expressions. I'm new to Java and don't know much about Java regexes.

Regex that I want to convert are very similar to this

Text =~ /(^FOO[0-9]{4})|(^BAR[0-9]{3})/

See if string matches to either FOO4823 BAR943 (FOO and 4 numbers or BAR and 3 numbers). How would I rewrite this in Java? Are there any simple rules to convert them?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
sublime
  • 4,013
  • 9
  • 53
  • 92
  • Start here: https://docs.oracle.com/javase/tutorial/essential/regex/? Come back when you will have problems with Java code. – Pshemo May 18 '15 at 21:38
  • What have you tried? Did you do any research on a modern website called google? and Oracle documentation? http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html – SwiftMango May 18 '15 at 21:40
  • I don't know any PHP. Does `=~` grab the part that was matched by the regex? What happens if there's more than one match? – markspace May 18 '15 at 21:46
  • @markspace It's perl. It just matches with the pattern and returns true or false. That is all I need to know. If the pattern matches or not. – sublime May 18 '15 at 21:50
  • @sublime Ah, OK. You have two answers below. Pick one. – markspace May 18 '15 at 21:56
  • 1
    There are construct differences between Perl and Java, but with your regex the constructs are identical. Are you trying to do Java regex without having to learn the standard Regex function calls? This is not a good start. –  May 18 '15 at 23:10

2 Answers2

1

It would be pretty similar.

Pattern pattern = Pattern.compile("(^FOO[0-9]{4})|(^BAR[0-9]{3})");
System.out.println(pattern.matcher("FOO4823").find());
System.out.println(pattern.matcher("BAR943").find());

Take a look at the test here

Nat
  • 3,587
  • 20
  • 22
0

To re-write this in Java, you want something like

String text = ...
Matcher matcher = Pattern.compile("(^FOO[0-9]{4})|(^BAR[0-9]{3})").matcher( text );
if( matcher.find() ) {  
  // ... it was found
}

As for a guide converting Perl to Java, there's a pretty good discussion in this StackOverflow question.

Community
  • 1
  • 1
markspace
  • 10,621
  • 3
  • 25
  • 39