How do you match military time? [duplicate] - java

This question already has answers here:
Invalid escape sequence \d
(2 answers)
Closed 10 years ago.
I'm trying to create a valid Java regex for matching strings representing standard "military time":
String militaryTimeRegex = "^([01]\d|2[0-3]):?([0-5]\d)$";
This gives me a compiler error:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
Where am I going wrong?!?

Make sure you use double backslashes for escaping characters:
String militaryTimeRegex = "^([01]\\d|2[0-3]):?([0-5]\\d)$";
Single backslashes indicate the beginning of an escape sequence. You need to use \\ to get the character as it appears in the String.
To answer your comment, you are currently only matching 19:00. You need to account for the additional :00 at the end of the String in your pattern:
String militaryTimeRegex = "^([01]\\d|2[0-3]):?([0-5]\\d):?([0-5]\\d)$";

In Java, you need to double-escape all the \ characters:
String militaryTimeRegex = "^([01]\\d|2[0-3]):([0-5]\\d):([0-5]\\d)$";
Why? because \ is the escape character for strings, and if you need a literal \ to appear somewhere inside a string, then you have to escape it, too: \\.

According to the error message \d does not exist. Escape it with \\d

Although \d is valid regex syntax, you need to escape the backslash in the Java string:
String militaryTimeRegex = "^([01]\\d|2[0-3]):?([0-5]\\d)$";

Related

Java Regular Expression - how to use backslash [duplicate]

This question already has answers here:
java, regular expression, need to escape backslash in regex
(4 answers)
Closed 6 years ago.
I am really confused with how to escape. Sometimes I just need to prepend a backslash but sometimes I need to prepend double backslash like "\\.".
Could any one tell me why?
Also, could anyone give me an explanation of difference in
String.split("\t"),
String.split("\\t"),
String.split("\\\t"),
String.split("\\\\t")?
Backslash is special character in string literals - we can use it to create \n or escape " like \".
But backslash is also special in regular expression engine - for instance we can use it to use default character classes like \w \d \s.
So if you want to create string which will represent regex/text like \w you need to write it as "\\w".
If you want to write regex which will represent \ literal then text representing such regex needs to look like \\ which means String representing such text needs to be written as "\\\\".
In other words we need to escape backslash twice:
- once in regex \\
- and once in string "\\\\".
If you want to pass to regex engine literal which will represent tab then you don't need to escape backslash at all. Java will understand "\t" string as string representing tab character and you can pass such string to your regex engine without problems.
For our comfort regex engine in Java interprets text representing \t (also \r and \n) same way as string literals interpret "\t". In other words we can pass to regex engine text which will represent \ character and t character and be sure that it will be interpreted as representation of tab character.
So code like split("\t") or split("\\t") will try to split on tab.
Code like split("\\\\t") will try to split text not on tab character, but on \ character followed by t. It happens because "\\\\" as explained represents text \\ which regex engine sees as escaped \ (so it is treated as literal).

How to split a string with double quotes " as the delimiter?

I tried splitting like this-
tableData.split("\\"")
but it does not work.
It seems that you tried to escape it same way as you would escape | which is "\\|". But difference between | and " is that
| is metacharacter in regex engine (it represents OR operator)
" is metacharacter in Java language in string literal (it represents start/end of the string)
To escape any String metacharacter (like ") you need to place before it other String metacharacter responsible for escaping which is \1. So to create String which would contain " like this is "quote" you would need to write it as
String s = "this is \"quote\"";
// ^^ ^^ these represent " literal, not end of string
Same idea is applied if we would like to create \ literal (we would need to escape it by placing another \ before it). For instance if we would want to create string representing c:\foo\bar we would need to write it as
String s = "c:\\foo\\bar";
// ^^ ^^ these will represent \ literal
So as you see \ is used to escape metacharacters (make them simple literals).
This character is used in Java language for Strings, but it also is used in regex engine to escape its metacharacters:
\, ^, $, ., |, ?, *, +, (, ), [, {.
If you would like to create regex which will match [ character you will need to use regex \[ but String representing this regex in Java needs to be written as
String leftBracketRegex = "\\[";
// ^^ - Remember what was said earlier?
// To create \ literal in String we need to escape it
So to split on [ we would need to invoke split("\\[") because regex representing [ is \[ which needs to be written as "\\[" in Java.
Since " is not special character in regex but it is special in String we need to escape it only in string literal by writing it as
split("\"");
1) \ is also used to create other characters line separators \n, tab \t. It can also be used to create Unicode characters like \uXXXX where XXXX is index of character in Unicode table in hexadecimal form.
You have escaped the \ by putting in \ twice, try
tableData.split("\"")
Why does this happen?
A backslash escapes the following character. Since the next character is another backslash, the second backslash will be escaped, thus the doublequote won't.
Your resulting escaped string is \", where it should really be just ".
Edit:
Also keep in mind, that String.split() interprets its pattern parameter as a regular expression, which has several special characters, which have to be escaped in the resulting string.
So if you want split by a .(which is a special regex character), you need to specify it as String.split("\\."). The first backslash escapes the escaping function of the second backlash and would result in "\.".
In case of regex characters you could also just use Pattern.quote(); to escape your desired delimiter, but this is far out of the scope the question orignally had.
Try with single backslash \
tableData.split("\"")
Try like this by escaping " with single backslash \ :
tableData.split("\"")
You are not escaping properly. The snippet code will not even compile because of it. The correct way to do it is
tableData.split("\"");
A single backslash will do the trick.
Like this:
tableData.split("\"");
You can actually split without the backward slash. You only have to use single quote
tableData.split('"');

java regex expression escape characters

Hi i'm trying to split a string separated by vertical bars. for example:
String str = "a=1|b=2";
In java, we should do like this:
str.split("\\|");
If I use a single slash:
str.split("\|");
compiler gives errors:
Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
Can anyone explain me why this happens? thanks!
Backslash \ is a special character. In the Java world it is used to escape a character.
The pipe | is a special character in the Regex world, which means "OR".
To use the pipe as a separator you need to escape it(so it can be recognized during the regex parsing), so you need to get this in your regex: \|.
But as backshlash is a special character in Java and that you are using a String object, you have to escape the backslash so it can be interpreted as the final expected final result: \|
To do so, you simply escape backslash with another backslash: \\|
The first backslash escapes the second backslash (java requirement) which escapes the pipe (regex requirement).
In Java strings, a backslash needs to be escaped with another backslash. So, while the "canonical" form of the regex is indeed \|, as a Java string, this must be written "\\|".

Replace backslash with double backslash [duplicate]

This question already has answers here:
String.replaceAll single backslashes with double backslashes
(5 answers)
Closed 6 years ago.
I want to change the backslash in a string to double backslash.
I have
String path = "C:\Program Files\Text.txt";
and I want to change it to
"C:\\Program Files\\Text.txt"
replaceAll is using regex, and since you don't need to use regex here simply use
path = path.replace("\\", "\\\\");
\ is special in String literals. For instance it can be used to
create special characters like tab \t, line separators \n \r,
or to write characters using notation like \uXXXX (where X is hexadecimal value and XXXX represents position of character in Unicode Table).
To escape it (and create \ character) we need to add another \ before it.
So String literal representing \ character looks like "\\". String representing two \ characters looks like "\\\\".
Using String#replace()
String s= "C:\\Program Files\\Text.text";
System.out.println(s.replace("\\", "\\\\"));

Java - Escaping Meta-characters [ and ] in Regex [duplicate]

This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
Closed 3 years ago.
I am attempting to replace the first occurrence of the string "[]" in another string:
aString.replaceFirst("[]", "blah");
I get the error:
java.util.regex.PatternSyntaxException: Unclosed character class near index 1 []
[ and ] are obviously metacharacters, however when I try to escape them with a \
eclipse complains that it is not a valid escape sequence.
I've looked but couldn't find, what am I missing?
Thank You
Regex patterns use \ as escape character, but so does Java. So to get a single escape (\) in a regex pattern you should write: \\. To escape an escape inside a regex, double the pattern: \\\\.
Of course that's extremely tedious, made all the worse because regexes have a ton of escape sequences like that. Which is why Java regexes also support “quoting” litteral parts of the pattern and this allows you to write your pattern as: \\Q[]\\E.
EDIT: As the other answer hints at: java.util.regex.Pattern.quote() performs this wrapping between \\Q and \\E.
Try \\[ and \\]. You need to double escape, because \ is also an escape character for strings (as is \" when you want to have double-quotes in your text). Therefore to get a \ in your string you have to use \\.
aString.replaceFirst("\\[\\]", "blah");
or in the more general case
aString.replaceFirst(java.util.regex.Pattern.quote("[]"), "blah");

Categories

Resources