All groovy special character #{\'}${"}/', needs to be replaced by \ in front in a groovy string dynamically
input : anish$spe{cial
output : anish\$spe\{cial
input : anish}stack{overflow'
output : anish\}stack\{overflow\'
I have written a sample program in Java, that i want in groovier way
import java.util.regex.*;
import java.io.*;
/**
*
* #author anish
*
*/
public class EscapeSpecialChar {
public static void main(String[] args) throws IOException {
inputString();
}
private static void inputString() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter string to find special characters: ");
String string = in.readLine();
// Escape the pattern
string = escapeRE(string);
System.out.println("output: -- " + string);
}
// Returns a pattern where all punctuation characters are escaped.
static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
public static String escapeRE(String str) {
return escaper.matcher(str).replaceAll("\\\\$1");
}
}
Enter string to find special characters: $Anish(Stack%1231+#$124{}
output: -- \$Anish\(Stack\%1231\+\#\$124\{\}
This does what your Java code does:
System.console().with {
def inStr = readLine 'Enter string to find special characters: '
def outStr = inStr.replaceAll( /([^a-zA-Z0-9])/, '\\\\$1' )
println "Output: $outStr"
}
I am still dubious that what I think you are doing is a good idea though... ;-)
Related
import java.io.IOException;
import java.util.Scanner;
public class MainTraining {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
int countOfStrangers = scanner.nextInt();
String[] name = new String[countOfStrangers];
System.out.println(scanner.nextLine());
}
}
It will output nothing.
Why?
that is only first part of my programm, so that separately this code has no sense
As i undersood, there are some troubles if you use nextLine after nextInt. To solve this problem you can read int with nextLine and after that parse it to int. Also you can create two scanners: one for ints and one for Strings
Full answer is here: Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?
I encountered a problem that the following code doesn't work. I ran the code in Java SE 11 (11.0.8), Eclipse 2020-06, Windows 10.
Use String Final Variable with Ternary Operator: Doesn't work
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
final String caseStr = true ? "abc" : "def";
switch (switchVar) {
case caseStr: System.out.println("Doesn't work");
}
}
}
It has a compile time error: java.lang.Error: Unresolved compilation problem: case expressions must be constant expressions.
However, according to JLS §4.12.4 and JLS §15.28, the String type can be a final variable and ternary operator can also be counted as constant expression.
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression.
A constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
...
The ternary conditional operator ? :
Simple names that refer to constant variables
I did some more tests which showed either one of these points works if not combined together.
Directly use constant expression as case constant: No Problem
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
switch (switchVar) {
case true ? "abc" : "def": System.out.println("works");
}
}
}
Use String constant variable without ternary operator: No Problem
public class Tester {
public static void main(String[] args) {
String switchVar = "abc";
final String VAR_A = "a";
final String VAR_BC = "bc";
final String CASE = VAR_A + VAR_BC;
switch (switchVar) {
case CASE : System.out.println("works");
}
}
}
Use int with ternary operator instead of String: No Problem
public class Tester {
public static void main(String[] args) {
int switchVar = 10;
final int CASE = 3 > 2 ? 10 : 0;
switch (switchVar) {
case CASE : System.out.println("works");
}
}
}
Could anyone help me please?
With kindly help of others, it is sure now this is a bug of eclipse.
I have reported the bug to eclipse. (Bugzilla – Bug 566332)
I've created file GroovyAnsi.groovy and code is below:
Source is https://gist.github.com/tvinke/db4d21dfdbdae49e6f92dcf1ca6120de
Now, please help me to call this function in my jenkins groovy script to color the output..
i could not use this function as i'm getting below error:
groovy.lang.MissingPropertyException: No such property: out for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
// Ansi colors in Groovy
// Author: Ted Vinke
import static Ansi.*
println color("BOLD", Ansi.BOLD)
println color("ITALIC", Ansi.ITALIC)
println color("UNDERLINE", Ansi.UNDERLINE)
println color("BLINK", Ansi.BLINK)
println color("RAPID_BLINK", Ansi.RAPID_BLINK)
println color("REVERSE_VIDEO", Ansi.REVERSE_VIDEO)
println color("INVISIBLE_TEXT", Ansi.INVISIBLE_TEXT)
println color("RED", Ansi.RED)
println color("BLACK", Ansi.BLACK)
println color("BOLD", Ansi.BOLD)
println color("GREEN", Ansi.GREEN)
println color("YELLOW", Ansi.YELLOW)
println color("BLUE", Ansi.BLUE)
println color("MAGENTA", Ansi.MAGENTA)
println color("CYAN", Ansi.CYAN)
println color("WHITE", Ansi.WHITE)
println color("DARK_GRAY", Ansi.DARK_GRAY)
println color("LIGHT_BLUE", Ansi.LIGHT_BLUE)
println color("LIGHT_GREEN", Ansi.LIGHT_GREEN)
println color("LIGHT_CYAN", Ansi.LIGHT_CYAN)
println color("LIGHT_RED", Ansi.LIGHT_RED)
println color("LIGHT_PURPLE", Ansi.LIGHT_PURPLE)
println color("LIGHT_YELLOW", Ansi.LIGHT_YELLOW)
println(
[
'Look', Ansi.LIGHT_RED,
'ma', Ansi.REVERSE_VIDEO,
',', Ansi.GREEN,
'no ', Ansi.MAGENTA,
'hands!', Ansi.LIGHT_YELLOW
]
.collate(2)
.collect { pair ->
color(pair.first(), pair.last())
}.join(' ')
)
/**
* Small ANSI coloring utility.
*
* #see http://www.bluesock.org/~willg/dev/ansi.html
* #see https://gist.github.com/dainkaplan/4651352
*/
class Ansi {
static final String NORMAL = "\u001B[0m"
static final String BOLD = "\u001B[1m"
static final String ITALIC = "\u001B[3m"
static final String UNDERLINE = "\u001B[4m"
static final String BLINK = "\u001B[5m"
static final String RAPID_BLINK = "\u001B[6m"
static final String REVERSE_VIDEO = "\u001B[7m"
static final String INVISIBLE_TEXT = "\u001B[8m"
static final String BLACK = "\u001B[30m"
static final String RED = "\u001B[31m"
static final String GREEN = "\u001B[32m"
static final String YELLOW = "\u001B[33m"
static final String BLUE = "\u001B[34m"
static final String MAGENTA = "\u001B[35m"
static final String CYAN = "\u001B[36m"
static final String WHITE = "\u001B[37m"
static final String DARK_GRAY = "\u001B[1;30m"
static final String LIGHT_RED = "\u001B[1;31m"
static final String LIGHT_GREEN = "\u001B[1;32m"
static final String LIGHT_YELLOW = "\u001B[1;33m"
static final String LIGHT_BLUE = "\u001B[1;34m"
static final String LIGHT_PURPLE = "\u001B[1;35m"
static final String LIGHT_CYAN = "\u001B[1;36m"
static String color(String text, String ansiValue) {
ansiValue + text + NORMAL
}
}
You must provide your class Ansi to the Jenkins classpath. You could create a jar with Ansi class and copy this jar in the Jenkins classpath or you must declare Ansi class in each groovy script that you use in Jenkins.
I've very simple grammar which tries to match 'é' to token E_CODE.
I've tested it using TestRig tool (with -tokens option), but parser can't correctly match it.
My input file was encoded in UTF-8 without BOM and I've used ANTLR version 4.4.
Could somebody else also check this ? I got this output on my console:
line 1:0 token recognition error at: 'Ă'
grammar Unicode;
stat:EOF;
E_CODE: '\u00E9' | 'é';
I tested the grammar:
grammar Unicode;
stat: E_CODE* EOF;
E_CODE: '\u00E9' | 'é';
as follows:
UnicodeLexer lexer = new UnicodeLexer(new ANTLRInputStream("\u00E9é"));
UnicodeParser parser = new UnicodeParser(new CommonTokenStream(lexer));
System.out.println(parser.stat().getText());
and the following got printed to my console:
éé<EOF>
Tested with 4.2 and 4.3 (4.4 isn't in Maven Central yet).
EDIT
Looking at the source I see TestRig takes an optional -encoding param. Have you tried setting it?
This is not an answer but a large comment.
I just hit a snag with Unicode, so I thought I would test this. Turned out I wrongly encoded the input file, but here is the test code, everything is default and working extremely well in ANTLR 4.10.1. Maybe of some use:
grammar LetterNumbers;
text: WORD*;
WS: [ \t\r\n]+ -> skip ; // toss out whitespace
// The letters that return Character.LETTER_NUMBER to Character.getType(ch)
// The list: https://www.compart.com/en/unicode/category/Nl
// Roman Numerals are the best known here
WORD: LETTER_NUMBER+;
LETTER_NUMBER:
[\u16ee-\u16f0]|[\u2160-\u2182]|[\u2185-\u2188]
|'\u3007'
|[\u3021-\u3029]|[\u3038-\u303a]|[\ua6e6-\ua6ef];
And the JUnit5 test that goes with that:
package antlerization.minitest;
import antlrgen.minitest.LetterNumbersBaseListener;
import antlrgen.minitest.LetterNumbersLexer;
import antlrgen.minitest.LetterNumbersParser;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.junit.jupiter.api.Test;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class MiniTest {
static class WordCollector extends LetterNumbersBaseListener {
public final List<String> collected = new LinkedList<>();
#Override
public void exitText(LetterNumbersParser.TextContext ctx) {
for (TerminalNode tn : ctx.getTokens(LetterNumbersLexer.WORD)) {
collected.add(tn.getText());
}
}
}
private static ParseTree stringToParseTree(String inString) {
Lexer lexer = new LetterNumbersLexer(CharStreams.fromString(inString));
CommonTokenStream tokens = new CommonTokenStream(lexer);
// "text" is the root of the grammar tree
// this returns a sublcass of ParseTree: LetterNumbersParser.TextContext
return (new LetterNumbersParser(tokens)).text();
}
private static List<String> collectWords(ParseTree parseTree) {
WordCollector wc = new WordCollector();
(new ParseTreeWalker()).walk(wc, parseTree);
return wc.collected;
}
private static String joinForTest(List<String> list) {
return String.join(",",list);
}
private static String stringInToStringOut(String parseThis) {
return joinForTest(collectWords(stringToParseTree(parseThis)));
}
#Test
void unicodeCharsOneWord() {
String res = stringInToStringOut("ⅣⅢⅤⅢ");
assertThat(res,equalTo("ⅣⅢⅤⅢ"));
}
#Test
void escapesOneWord() {
String res = stringInToStringOut("\u2163\u2162\u2164\u2162");
assertThat(res,equalTo("ⅣⅢⅤⅢ"));
}
#Test
void unicodeCharsMultipleWords() {
String res = stringInToStringOut("ⅠⅡⅢ ⅣⅤⅥ ⅦⅧⅨ ⅩⅪⅫ ⅬⅭⅮⅯ");
assertThat(res,equalTo("ⅠⅡⅢ,ⅣⅤⅥ,ⅦⅧⅨ,ⅩⅪⅫ,ⅬⅭⅮⅯ"));
}
#Test
void unicodeCharsLetters() {
String res = stringInToStringOut("Ⅰ Ⅱ Ⅲ \n Ⅳ Ⅴ Ⅵ \n Ⅶ Ⅷ Ⅸ \n Ⅹ Ⅺ Ⅻ \n Ⅼ Ⅽ Ⅾ Ⅿ");
assertThat(res,equalTo("Ⅰ,Ⅱ,Ⅲ,Ⅳ,Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ,Ⅻ,Ⅼ,Ⅽ,Ⅾ,Ⅿ"));
}
}
Your grammar file is not saved in utf8 format.
Utf8 is default format that antlr accept as input grammar file, according with terence Parr book.
how to alter a substring of a string using replaceAll()
for example using the regular expression "1[a-z]+" (split with "X") and the code:
"this is an example 1one"
should produce:
"this is an example 1Xone"
Try this:
class Test {
public static void main(String[] args) {
String str = "this is an example 1one";
str = str.replaceAll("1([a-z]+)", "1X$1");
System.out.println(str);
}
}