pattern matching and range checking with regex in java

My application will basically accept user input via the main(String[] args) method. I have been trying to figure a way to do some checking with that input using a patter matcher.

Each valid input consists basically of a single character: (blanks should be ignored)

* 'R' or 'r' - replay * 'Q' or 'q' - quit * [1-6] - perform tasks 1 .. 6

If the user input is invalid - which means if we detect anything different than the above, then the application will quit after displaying an error message.

So, all the logic within the main method would be in a single big conditional:

if(Pattern.matches("[RQrq1-6]*", args[0]){ }

I have some difficulty grasping the matches method with regex involved (The above doesn't work) and I would like to avoid having multiple if-else conditions to check each valid input individually.

Can this be achieved with pattern matcher with range checking at the same time?

Thanks for any hints!

--------------Solutions-------------

Your regex isn't quite right.

When you write: [RQrq1-6]*

You're saying match zero or more repetitions of any character in the square brackets...

Try this [RQrq1-6] - which means match exactly one.

I wrote a little "spike" program:

import java.util.regex.Pattern;

public class Spike {

public static void main(String[] args) {
testIt("Q");
testIt("q");
testIt("z");
testIt("Z");
testIt("R");
testIt("r");
testIt("0");
testIt("1");
testIt("2");
testIt("3");
testIt("4");
testIt("5");
testIt("6");
testIt("7");
testIt("02");
testIt("11");
testIt("17");
testIt(""); // should fail, used to pass with the question's regex

}

public static void testIt(String sample) {
System.out.print(sample+" ");
if (Pattern.matches("[RQrq1-6]*", sample)) {
System.out.println("match");
} else {
System.out.println("fail");
}
}

}

Output was this:

Q match
q match
z fail
Z fail
R match
r match
0 fail
1 match
2 match
3 match
4 match
5 match
6 match
7 fail
02 fail
11 match
17 fail
match

Having removed the star in the regex:

Q match
q match
z fail
Z fail
R match
r match
0 fail
1 match
2 match
3 match
4 match
5 match
6 match
7 fail
02 fail
11 fail
17 fail
fail

How to ignore the blanks

Substitute this version of testit:

public static void testIt(String sample) {
System.out.print(sample+" ");

Pattern pattern = Pattern.compile("\\s*([RQrq1-6])\\s*");
Matcher matcher = pattern.matcher(sample);

if (matcher.matches()) {
System.out.println("match '"+matcher.group(1)+"'");
} else {
System.out.println("fail");
}
}

Here are the critical lines of the output:

testIt(" 6");// ignore space tests
testIt(" 7");// ignore space tests
testIt("6 ");// ignore space tests
testIt("7 ");// ignore space tests

6 match '6'
7 fail
6 match '6'
7 fail

It uses a concept called a "capture group". A capture group is a section of a regex which is assigned a number so that the specific string of symbols that matched can be extracted. We're using a capture group here to pull the symbol out from the optional whitespace.

I would be tempted not to do this with a regexp, since it'll only match and extract a particular pattern, and not really help with deciding what to do for a particular string (using one regexp).

Instead, I'd check out a command line option library such as Apache Commons CLI. It's much more appropriate for what you require.

I think you need to match each argument passed in. So:

for(int i = 0; i < args.length; i++) {
if (Pattern.matches("[RQrq1-6]+", args[i]){
<do stuff>
}
}

The following class works fine for me (exactly as I'd expect anyway):

public class Test{
public static void main(String[] args) throws Exception {
if(java.util.regex.Pattern.matches("[RQrq1-6]*", args[0])){
System.out.println("OK: "+args[0]);
} else {
System.out.println("Not OK: " +args[0]);
}
}
}

Example:

[email protected]:~$ java Test rr
OK: rr
[email protected]:~$ java Test rrRR
OK: rrRR
[email protected]:~$ java Test rrRRa
Not OK: rrRRa

Now, you're probably trying to match against all characters on the command line. The command interpreter separates those out into separate strings before launching your application. You could do as Myles suggests, but then you'll process some commands before detecting bad input. You could do this instead:

String myargs = "";
for (String arg : args) {
myargs += arg;
}
if(java.util.regex.Pattern.matches("[RQrq1-6]*", myargs)){
...

If I read your question right, you want to call your program like this:

$ myprog 153r34r2q

Then, your program goes through that string of single letter commands and performs them (perhaps to something you pass in in further arguments).

For that, your regex solution is almost OK (use /[RrQq1-6]+/ instead of /[RrQq1-6]*/).

However, I suspect that you actually want to run your program, then accept user commands while the program is running (this assumption is caused by the names of your commands "replay" and "quit", which don't make much sense otherwise). For that, args[] is not suited at all. Instead, you will have to use a main loop which accepts single keystrokes as input. In this case, I wouldn't use a regular expression to test a single character, but use a switch clause for dispatching to the different commands that has a default case to catch invalid input.

Edit: After having read your comment, I propose that you might want to use something along the Command Pattern.

Category:java Time:2009-11-14 Views:1
Tags: regex java

Related post

  • How to get pattern matching in php array using RegEx 2012-03-06

    I have following set of an array array('www.example.com/','www.example.com','www.demo.example.com/','www.example.com/blog','www.demo.com'); and I would like to get all element which matching following patterns, $matchArray = array('*.example.com/*','

  • Regex pattern matching doesn't work specifc string in java 2011-12-28

    I was using a REGEX pattern in java (given below): for the string: It works fine. But when I tried using the below pattern: for the string:str = Sorry about the image upload. Looks like the character '[]' in a00[] is encoded differently on the browse

  • Erlang pattern matching performance 2011-01-22

    new to Erlang. I am about to start writing some code. The solution I have in mind can go one of two ways. I can do a bunch of mathematical calculations, or I can code this up largely as pattern matching. When I say "pattern matching," I DO NOT mean r

  • Explaining pattern matching vs switch 2008-10-14

    I have been trying to explain the difference between switch statements and pattern matching(F#) to a couple of people but I haven't really been able to explain it well..most of the time they just look at me and say "so why don't you just use if..then

  • Pattern matching with guards vs if/else construct in F# 2011-11-02

    In ML-family languages, people tend to prefer pattern matching to if/else construct. In F#, using guards within pattern matching could easily replace if/else in many cases. For example, a simple delete1 function could be rewritten without using if/el

  • Concatenation of a string and a regex in java 2014-06-03

    I want to concatenate a regex and a string and want to compare the resultant string with another string.How can I do that in java? import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatching { public static void main(St

  • Regex to match 4 repeated letters in string using java pattern 2010-04-12

    i want to match something like aaaa, aaaad, adjjjjk. Something like this ([a-z])\1+ was used to match the repeated characters but i am not able to figure this out for 4 letters. --------------Solutions------------- Not knowing about the finite repeti

  • Replacing character with File.separator using java.regex Pattern Matcher 2011-01-22

    I have a field called 'path' in back end database, which stores the path to certain resource. Instead of storing lots of backslashed (escaped) path for windows path, my idea is to let user enter the path with certain character as file separator (inde

  • C# RegEx pattern for scheduler (date / time alike pattern matcher) 2011-07-26

    Can someone guide me in the direction on how to get a RegEx pattern matching the following possibilities for C#?: RegEx using 4 parameters First 2 params can get the star (*) character as value 1st param, if not a *, needs to be an int between (inclu

  • PHP RegEx pattern matching - beginner questions to get me started 2011-11-07

    This is a homework assignment and my first experience using RegEx. I am starting to grasp the syntax and symbols used and can do some simple pattern matching/manipulation, but can't quite foresee how to achieve some of the goals of this assignment. I

  • Regex: String.split and Pattern.matches does not agree with each other 2012-04-28

    I'm practicing my regex lookarounds and, to do so, I'm trying to extract the table name from an SQL insert statement. I have the regex (?<=INSERT INTO )\w+(?= (\(|VALUES).+) and I'm testing it on the String INSERT INTO tests VALUES (regex, test).

  • What do these regex Patterns Match? 2009-05-23

    I am new to regex in PHP and understand the basic patterns however the ones below are a bit complex and I don't understand what the following pattern matches: $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,[email protected]\[\]+]*)#... "<a href=''

  • Understanding regex criteria in pattern match 2009-08-31

    I am trying to determine what the following pattern match criteria allows me to enter: \s*([\w\.-]+)\s*=\s*('[^']*'|"[^"]*"|[^\s]+) From my attempt to decipher (by looking at the regex's I do understand) it seems to say I can start with any character

  • How can I match on, but exclude a regex pattern? 2010-06-09

    I have this URL: http://example.com/createSend/step4_1.aspx?cID=876XYZ964D293CF&snap=true&jlkj=kjhkjh& And this regex pattern: cID=[^&]* Which produces this result: cID=87B6XYZ964D293CF How do I REMOVE the "cID="? Thanks -------------

  • How can I pattern match on a range in Scala? 2010-07-01

    In Ruby I can write this: case n when 0...5 then "less than five" when 5...10 then "less than ten" else "a lot" end How do I do this in Scala? Edit: preferably I'd like to do it more elegantly than using if. --------------Solutions------------- Insid

  • What are good Perl Pattern-matching / Regex Modules? 2010-07-15

    I've been having a need to do a lot of regex / pattern-matching stuff lately and, in looking at different examples / forum posts from my web searches it seems people sometimes mention that perl has good modules to help in simplifying pattern matching

  • Regex Pattern Matching Concatenation 2011-08-08

    Is it possible to concatenate the results of Regex Pattern Matching using only Regex syntax? The specific instance is a program is allowing regex syntax to pull info from a file, but I would like it to pull from several portions and concatenate the r

  • Java Regex pattern matching 2011-08-23

    I am developing a text highlighter in a file using the java regex pattern matching. Following is a code snapshot of it SearchQuery=preprocessedModifiedArrayList.get(i)+[\\w\\s\\W]*?"; pattern = Pattern.compile(SearchQuery); Matcher matcher = pattern.

  • How to Convert Regex Pattern Match to Lowercase for URL Standardization/Tidying 2011-10-12

    I am currently trying to convert all links and files and tags on my site from UPPERCASE.ext and CamelCase.ext to lowercase.ext. I can match the links in pages using a regular expression match for href="[^"]*" and src="[^"]*" This seems to work fine f

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 4.746 (s). 13 q(s)