substring using \(backslash) in java - java

I want to get file name from complete path of file.
Input : "D://amol//1/\15_amol.jpeg"
Expected Output : 15_amol.jpeg
I have written below code for this
public class JavaApplication9 {
public static void main(String[] args) {
String fname="D://amol//1/\15_amol.jpeg";
System.out.println(fname.substring(fname.lastIndexOf("/")));
System.out.println(fname.substring(fname.lastIndexOf("\\")));
}
}
but getting below output :
_amol.jpeg
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
at java.lang.String.substring(String.java:1927)
at javaapplication9.JavaApplication9.main(JavaApplication9.java:6)
C:\Users\lakhan.kamble\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53:
Java returned: 1

The string \15 is an "octal escape" for the carriage return character (0x0d, 13 decimal). There are two possibilities here.
You really meant \15 to be the octal escape, in which case you are trying to create a filename with an embedded newline. The actual contents of fname in this case could be expressed as
"D://amol//1/" + "\n" + "_amol.jpeg";
Windows will prevent that from happening and your program will throw an IOException.
You really meant
String fname="D://amol//1/\\15_amol.jpeg";
In this case the extra backslash is redundant and will be ignored by Windows because the filename will resolve (in Windows path terms) to D:\amol\1\\15_amol.jpeg and adjacent directory separators collapse to a single separator. So you could just omit the extra backslash altogether without changing the effective path.
As to your exception, the string as shown DOES NOT contain a backslash character (case 1 above), so
fname.lastIndexOf("\\")
returned -1, causing the exception

Related

Antlr4: Confusing error message (concatenates correct and incorrect lines) for Java grammar

I am trying to build my own parser based on the existing Java grammar.
Even if I use the Java7 grammar from the source repo, generate the parser and use the TestRig from antlr-4.9.3-complete.jar given the code:
1 public class Test {
2 public static void main() {
3 test
4 int b = 1;
5 }
6 }
I get the following error:
line 4:8 no viable alternative at input 'test\n int'
So for some reason it concatenates the incorrect "test" line with correct "int" line.
Also it says "line 4:8" pointing at the "int" line when it should be pointing to "test" (line 3).
(In a regular Java editor I would see a correct error highlighting for the "test" word which would sound like):
"Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
What do I do to arrive at a similar error with ANTLR so it only picks on the wrong "test" line?
Most likely it's just my misunderstanding how antlr interprets the errors, then how would I get the listener to at least report correctly the starting line?
You can't compare a sophisticated editor/IDE with a parser (generated by ANTLR). A text editor/IDE knows more about the input source and can look up if test is a valid type, and give a meaningful error message if the type cannot be found.
ANTLR's parser rule "sees" test int b as an Identifier, an INT and another Identifier token and cannot match any parser rule for these tokens, resulting in the error starting at the identifier test.
For example, if class test {} was in the classpath, then input without int would be valid:
public class Test {
public static void main() {
test
/*int*/ a = 1;
}
}
It wouldn't compile of course, but the syntax would be correct:

Regex Expression working in Notepad++ but not Java

Okay, so i'm working on a problem I'd rather solve with regex, I test most of my regex expressions in Notepad++, This has worked fine after a few tweaks such as double escaping some things for java, However this regex expression throws an exception when run in java, however it runs in Notepad++ just fine, the idea if this code is to be able to mention a different player in the game with a highlighted name.
tldr; I'm trying to replace the first occurrence of a specific name in a message
I've tried looking around for a while but i haven't found a solution, so i thought i might as well ask here.
p.getName() simply returns a string (the players name)
String newmessage = message.replaceFirst("(?i)" + Pattern.quote(p.getName()) + "((?(?=\\s)|('|,|!))|$)", color + p.getName() + Color.toString(Color.getLastColorOf(message)));
However executing the code throws this exception
...at java.lang.Thread.run(Unknown Source) [?:1.8.0_202]
Caused by: java.util.regex.PatternSyntaxException: Unknown inline modifier near index 15
(?i)\QTauCubed\E((?(?=\s)|('|,))|$)
^
at java.util.regex.Pattern.error(Unknown Source) ~[?:1.8.0_202]...
And I'm not sure what it wants me to do, I don't see how this is not valid regex
This is the regex for Notepad++
(?i)Name((?(?=\s)|('|,|!))|$)
The above will match
Name's r
Name
Name test
Name,
Name!
But will not match
Nametest
That is what I intended it to do.
I vote for just using the pattern \bName\b along with String#replaceFirst:
String input = "Rename here is a Name and here is the same Name again.";
input = input.replaceFirst("\\bName\\b", "blah");
System.out.println(input);
This prints:
Rename here is a blah and here is the same Name again.

Groovy remove beginning of path

I'm trying to delete the beginning of a path that has '\' and ' ' in it. I seem to be getting the some issues saying escape character issue at character 3.
Example:
SomePath: C:\Users\ADMINISTRATOR\App Play\blah\blah
SomePath.replaceFirst('C:\\Users\\ADMINISTRATOR\\App Play\\', '');
Path should be blah\blah
I've tried:
SomePath.replaceFirst("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceFirst("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
SomePath.replaceAll("C:\Users\ADMINISTRATOR\App Play\", "");
SomePath.replaceAll("C:\\Users\\ADMINISTRATOR\\App Play\\", "");
SomePath.replaceAll("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
Just gave it a try... the examples with four backslashes work for me:
def somePath = "C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah"
println somePath
somePath.replaceFirst("C:\\\\Users\\\\ADMINISTRATOR\\\\App Play\\\\", "");
The problem is that the string needs one escaping \ and since the replaceFirst uses a regexp, the regexp-engine needs another \ to escape the \. The result are four backslashes.
Btw: you can use string operations to get your path, but you could also try file operations like this:
def root= new File("C:\\Users\\ADMINISTRATOR\\App Play\\")
def full= new File("C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah")
def relPath = root.toPath().relativize( full.toPath() ).toFile()
println relPath
(taken from https://gist.github.com/ysb33r/5804364)
You can tackle this problem differently. You could tokenize your input path using \ as a delimiter and then you could pick the last 2 elements (blah and blah) or skip first 4 elements (C:, Users, ADMINISTRATOR, App Play). It depends which assumption is easier to deduct for you. Consider following example:
def somePath = 'C:\\Users\\ADMINISTRATOR\\App Play\\blah\\blah'
// Build a new path by accepting the last 2 parts of the initial path
assert 'blah\\blah' == somePath.tokenize('\\')[-2..-1].join('\\')
// Build a new path by skipping the first 4 parts from initial path
assert 'blah\\blah' == somePath.tokenize('\\').drop(4).join('\\')
First option works better if you want only two last parts from the initial path. Second option works better if you can expect final path like blah\blah\blahhhh because you don't know how many nested children initial path contains and you want to start building a new path right after \App Play\ .

Scala RegEx String extractors behaving inconsistently

I have two regular expression extractors.
One for .java files and the other is for .scala files
val JavaFileRegEx =
"""\S*
\s+
//
\s{1}
([^\.java]+)
\.java
""".replaceAll("(\\s)", "").r
val ScalaFileRegEx =
"""\S*
\s+
//
\s{1}
([^\.scala]+)
\.scala
""".replaceAll("(\\s)", "").r
I want to use these extractors above to extract a java file name and a scala file name from the example code below.
val string1 = " // Tester.java"
val string2 = " // Hello.scala"
string1 match {
case JavaFileRegEx(fileName1) => println(" Java file: " + fileName1)
case other => println(other + "--NO_MATCH")
}
string2 match {
case ScalaFileRegEx(fileName2) => println(" Scala file: " + fileName2)
case other => println(other + "--NO_MATCH")
}
I get this output indicating that the .java file matched but the .scala file did not.
Java file: Tester
// Hello.scala--NO_MATCH
How is it that the Java file matched but the .scala file did not?
NOTE
[] denotes character class. It matches only a single character.
[^] denotes match anything except the characters present in the character class.
In your first regex
\S*\s+//\s{1}([^\.java]+)\.java
\S* matches nothing as there is space in starting
\s+ matches the space which is in starting
// matches // literally
\s{1} matches next space
You are using [^\.java] which says match anything except . or j or a or v or a which can be written as [^.jav].
So, the left string now to be tested is
Tester.java
(Un)luckily any character from Tester does not matches . or j or a or v until we encounter a .. So Tester is matched and then java is also matched.
In your second regex
\S*\s+//\s{1}([^\.scala]+)\.scala
\S* matches nothing as there is space in starting
\s+ matches the space which is in starting
// matches // literally
\s{1} matches next space
Now, you are using [^\.scala] which says that match anything except . or s or c or a or l or a which can be written as [^.scla].
You have now
Hello.scala
but (un)luckily Hello here contains l which is not allowed according to character class and the regex fails.
How to correct it?
I will modify only a bit of your regex
\S*\s+//\s{1}([^.]*)\.java
<-->
This says that match anything except .
You can also use \w here instead if [^.]
Regex Demo
\S*\s+//\s{1}([^.]*)\.scala
Regex Demo
There is no need of {1} in \s{1}. You can simply write it as \s and it will match exactly one space like
\S*\s+//\s([^.]*)\.java

Bizzare System.out.println() in Java Program

String messageFile = ... // Assume messageFile SHOULD have the string "MESSAGE"
System.out.println("The messageFile is: " + messageFile + "!!");
Normally, one would expect the above command to output:
The messageFile is: MESSAGE!!!!
However, I am receiving this instead:
!!e messageFile is: MESSAGE
See how the above statement, the "!!" points seem to wrap around the message. My theory is that the:
String messageFile = ...
contains more characters than my assumed "MESSAGE". As a result, it's wrapping the next input (in this case, the "!!") to the front of the System.out.println() message.
What character is causing this?
Extra info:
Btw, messageFile is being initialized by passing a command line argument to a java class, myClassA. myClassA's constructor uses a super() to pass the messageFile parameter to myClassB. myClassB passes messageFile into a function().
I would guess you have a stray carriage return (\r) within the messageFile variable that is unaccompanied by a line feed (\n).
EDIT - this tests as expected:
class Println {
public static void main(String[] args) {
System.out.println("xxxx this \rTEST");
}
}
Output:
TEST this
Your message variable possibly contains a '\r' (carriage return) or '\n' (line feed) character at the end. This may cause the cursor to return to the first column before printing the exclamation marks.
For debugging you should print the codepoint of each character of messageFile via codePointAt.
As as result you see exactly the content of messageFile.
Replace all carriage returns in the file with newlines and then replace all double-newlines with single-newlines:
messageFile.replace('\r', '\n').replace("\n\n", "\n)
Carriage returns should be banned :D

Categories

Resources