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);
}
}
Related
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.
The below code works just fine. But how can I get the user to input a string instead of and int to bring up either the "shop" or "inn" method?
ie. When "int a = navigate.nextInt();" is changed to "String a = navigate.nextString();" and the "if" and "if else" conditions are changed to "a == "shop" or "inn". The next line to run the correct method does nothing.
(I hope that made sense, see below)
import java.util.*;
public class ShopTest {
public static Scanner navigate = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Where to?\n Shop (1)\n Inn (2)");
int a = navigate.nextInt();
if (a == 1)
Shop();
else if (a == 2)
Inn();
}
public static void Shop() {
System.out.println("Welcome to my shop\nWould you like to see my wares?");
}
public static void Inn() {
System.out.println("**You enter the inn and approach the barkeep**\nHow can I help you?");
}
}
Try this
System.out.println("Where to?\n Shop \n Inn ");
String a = navigate.nextLine();
if (a.equals("Shop"))
Shop();
else if (a.equals("Inn"))
Inn();
}
Use .equal
== tests for reference equality (whether they are the same object).
.equal tests for value equality (whether they are logically
"equal").
More: How do I compare strings in Java?
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... ;-)
For example, I need to see if a string contains a substring, so I just do:
String helloworld = "Hello World";
if(helloworld.Contains("ello"){
//do something
}
but if I have an array of items
String helloworld = "Hello World";
String items = { "He", "el", "lo" };
I needed to create a function inside the String class that would return true if either of
the items inside the array is contained in the string, for example.
I would like to override the function Contains(string) with Contains(IEnumerable) for this scenario, instead of creating a function in another class. Is it possible to do this, and if so, how can we override the function? Thank you very much.
So here goes the complete solution (thanks guys):
public static bool ContainsAny(this string thisString, params string[] str) {
return str.Any(a => thisString.Contains(a));
}
You can't override the function, but you can make an extension method for this:
public static class StringExtensions {
public static bool ContainsAny(this string theString, IEnumerable<string> items)
{
// Add your logic
}
}
You'd then call this just like a normal method on a string, provided you reference the assembly and include the namespace:
String helloworld = "Hello World";
String[] items = new string[] { "He", "el", "lo" };
if (helloworld.ContainsAny(items)) {
// Do something
}
(Granted, you could call this "Contains", like the standard string method, but I would prefer to give it a more explicit name so it's obvious what you're checking...)
Why not keep things simple and use the Any extension method?
string helloworld = "Hello World";
string[] items = { "He", "el", "lo" };
if (items.Any(item => helloworld.Contains(item)))
{
// do something
}