Regulal Expression to match on all printable characters

Hi
I am trying to write a regular expression to match all printable character or more accuratly discard ASCII range 32 to 126.I thought it might be easier to match on any printable character.

However i can seem to get the RegExp to work in my java app.

I am trying

^[\w\d_~`!@#$%^&*()-+=<>?/\.,;:'"][}{\|]+$

but am not sure if its correct and not sure if i need to escape the \ character.

Help greatly appreciated.

My code is


public static void main(String[] args) {
          // Compile regular expression
            String patternStr =  "";
       
        //^[\w\d_~`!@#$%^&*()-+=<>?/\.,;:'"][}{\|]+$
       
//        String patternStr = "\\w";
        Pattern pattern = Pattern.compile(patternStr);
     
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String inputString = null;
       
        try {
              inputString = br.readLine();
        } catch (IOException ioe) {
           System.out.println("Unknown Error");
           System.exit(1);
        }

        Matcher matcher = pattern.matcher(inputString);
        boolean matchFound = matcher.find();    // true
       
        System.out.println("Match Found " + matchFound);


      }

MolkoAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
>>Oh, is there a reason you are reading throught the string in reverse order in the 2nd example ?

It makes altering the buffer in the loop less (un)problematic
0
 
CEHJCommented:
But is your intention to clean the string or just ignore it if it doesn't match?
0
 
CEHJCommented:
In this case it would be more efficient and probably more convenient to do something like


boolean stillValid = true;
for (int i;i < s.length() && stillValid;i++) {
	char c = s.charAt(i)
	stillValid = (c >= ' ' && c <= '~');
}

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
MolkoAuthor Commented:
Yes i intend to clean the string up
0
 
CEHJCommented:
Even more reason then to use the above (or a variant)
StringBuilder sb = new StringBuilder(line);
boolean stillValid = true;
for (int i = sb.length() - 1;i >= 0;i--) {
	char c = sb.charAt(i)
	if (c < ' ' || c > '~') {
		sb.deleteCharAt(i);
	}
}

Open in new window

0
 
MolkoAuthor Commented:
Ok, thank you. I've been struggling with a regular expression for ages. Thanks

Oh, is there a reason you are reading throught the string in reverse order in the 2nd example ?

0
 
MolkoAuthor Commented:
ok ...thanks for your help
0
 
CEHJCommented:
:-)
0
All Courses

From novice to tech pro — start learning today.