RegEx help to replace substring - java

I have a String:
StartTime-2014-01-14 12:05:00-StartTime
The requirement is to replace the timestamp with current timestamp.
I tried the below code which is not giving me the expected output:
String st = "StartTime-2014-01-14 12:05:00-StartTime";
String replace = "StartTime-2014-01-14 13:05:00-StartTime";
Pattern COMPILED_PATTERN = Pattern.compile(st, Pattern.CASE_INSENSITIVE);
Matcher matcher = COMPILED_PATTERN.matcher(DvbseContent);
String f = matcher.replaceAll(replace);
Expected Output is:
StartTime-<Current_Time_stamp>-StartTime

Or instead of Regex, you can just use indexOf and lastIndexOf:
String f = "StartTime-2014-01-14 12:05:00-StartTime";
String timestamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
.format(new java.util.Date());
String newString = f.substring(0, f.indexOf("-") + 1)
+ timestamp
+ f.substring(f.lastIndexOf("-"));
Output:
StartTime-2014-02-10 12:52:47-StartTime

You could match it like this:
(StartTime-).*?(-StartTime)
and replace it with this (or similar):
"$1" + current_time_stamp + "$2"
Example Java Code:
import java.util.*;
import java.util.Date;
import java.lang.*;
import java.io.*;
import java.util.regex.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
java.util.Date timestamp = new java.util.Date();
String search = "StartTime-2014-01-14 12:05:00-StartTime";
String regex = "(StartTime-).*?(-StartTime)";
String replacement = "$1"+ timestamp + "$2";
String result = search.replaceAll(regex, replacement);
System.out.println(result);
};
};
Output:
StartTime-Fri Feb 14 08:53:57 GMT 2014-StartTime

Related

How to split String using Regex specific String

I have a value(String) like "BLD00000001BLD00000002 BLD00000003, BLD00000004".
I want to use Regex """^BLD\d{8}"""
but it didn't work..
I want to return results like (BLD00000001','BLD00000002','BLD00000003 ... )
var regex = Regex("""[\{\}\[\]\/?.,;:|\) *~`!^\-_+<>#\#$%&\\\=\(\'\"]""")
val cvrtBldIds = bldIds.split(regex)
if (cvrtBldIds.joinToString(separator="").length % 11 != 0) {
throw BadRequestException("MSG000343", listOf("빌딩Id", "BLD[숫자8자리]"))
} else {
val res = cvrtBldIds
.filter{it.startsWith("BLD")} // BLD로 시작하는 것만 추출
.joinToString(separator = "','") // 아이디 앞뒤로 ',' 붙이기
bldIds = res
var sb = StringBuffer()
sb.append("'")
sb.append(bldIds)
sb.append("'")
input.bldId = sb.toString()
}
Do it as follows:
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "BLD00000001BLD00000002 BLD00000003, BLD00000004";
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile("BLD\\d{8}");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
list.add(matcher.group());
}
System.out.println(list);
}
}
Output:
[BLD00000001, BLD00000002, BLD00000003, BLD00000004]
Notes:
BLD\\d{8} means starting with BLD and then 8 digits.
Java regex tutorial: https://docs.oracle.com/javase/tutorial/essential/regex/
Seems you want to split on a space, or a comma-space combo, or between a digit and the text BLD. The following regex can do that:
,?\s|(?<=\d)(?=BLD)
See regex101 for demo.
Here is how you can extract BLD\d{8} pattern matches in Kotlin using .findall():
val text = """"BLD00000001BLD00000002 BLD00000003, BLD00000004"."""
val matcher = """BLD\d{8}""".toRegex()
println(matcher.findAll(text).map{it.value}.toList() )
// => [BLD00000001, BLD00000002, BLD00000003, BLD00000004]
See the Kotlin demo

Add comma separator between two strings which are in specific format

Have two strings in specific format.Need to add comma between two strings using regex.
String input1 = "\"abc_xyz\"";
String input2 = "\"ijk_bcd\"";
String result = (input1+input2).replaceAll("([^ ]) ", "$1,");
With the above regex I am getting result as
"abc_xyz" "ijk_bcd".
Expected output should look like
"abc_xyz","ijk_bcd".
My guess is that this expression might also solve the problem, yet it is unnecessary:
(.*")(".*)
Demo
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "(.*\")(\".*)";
final String string = input1+input2;
final String subst = "$1,$2";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
You could do
String joinedString = String.join(",", input1, input2);

How to avoid replacing specific words in a text in java

I have a method like this :
for(String abc:abcs){
xyz = abc.replaceAll(abc+"\\(", "_"+abc+"\\(");
}
How to avoid replacing few replacements which have specific prefixes for them in java
I tried this :
String data = "Today, abc.xyz is object oriented language";
String regex = "(?<!abc.)xyz";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(data);
System.out.println(matcher.find());
Does this work for you?
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String prefix = "abc";
String replaceWith = " text";
String input = "This xyz is an example xyz to show how you can replace certains values of the xyz.\n"
+ "The xyz can conain any arbitrary xyz, for example abc.xyz.";
Pattern pattern = Pattern.compile("[^" + prefix + "].xyz");
Matcher m = pattern.matcher(input);
while (m.find()) {
input = input.replace(m.group().substring(1), replaceWith);
}
System.out.println(input);
}
}

Java regex get exact token value

I've string like below , want to get the value of cn=ADMIN , but dont know how to get to using regex efficient way.
group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa
well ... like this?
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexSample {
public static void main(String[] args) {
String str = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
Pattern pattern = Pattern.compile("^.*/(.*)$");
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
String right = matcher.group(1);
String[] parts = right.split(",");
for (String part : parts) {
System.err.println("part: " + part);
}
}
}
}
Output is:
part: cn=ADMIN
part: cn=groups
part: dc=mi
part: dc=com
part: dc=usa
String bubba = "group:192.168.133.205:387/cn=ADMIN,cn=groups,dc=mi,dc=com,dc=usa";
String target = "cn=ADMIN";
for(String current: bubba.split("[/,]")){
if(current.equals(target)){
System.out.println("Got it");
}
}
Pattern for regex
cn=([a-zA-Z0-9]+?),
Your name will be in group 1 of matcher. You can extend character classes if you allow spaces etc.

Read string after " " and before "(" using split in java

I have txt file with line:
1st line - 20-01-01 Abs Def est (xabcd)
2nd line - 290-01-01 Abs Def est ghj gfhj (xabcd fgjh fgjh)
3rd line - 20-1-1 Absfghfgjhgj (xabcd ghj 5676gyj)
I want to keep 3 diferent String array:
[0]20-01-01 [1]290-01-01 [2] 20-1-1
[0]Abs Def est [1]Abs Def est ghj gfhj [2] Absfghfgjhgj
[0]xabcd [1]xabcd fgjh fgjh [2] xabcd ghj 5676gyj
Using String[] array 1 = myLine.split(" ") i only have piece 20-01-01 but i also want to keep other 2 Strings
EDIT: I want to do this using regular Expressions (text file is large)
This is my piece of code:
Please help, i searching, but does not found anything
Thx.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Comparator;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
public class Holiday implements Comparable<Date>{
Date date;
String name;
public Holiday(Date date, String name){
this.date=date;
this.name=name;
}
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("c:/holidays.txt"));
InputStreamReader isr = new InputStreamReader(fis, "windows-1251");
BufferedReader br = new BufferedReader(isr);
TreeSet<Holiday> tr=new TreeSet<>();
System.out.println(br.readLine());
String myLine = null;
while ( (myLine = br.readLine()) != null)
{
String[] array1 = myLine.split(" "); //OR use this
//String array1 = myLine.split(" ")[0];//befor " " read 1-st string
//String array2 = myLine.split("")[1];
//Holiday h=new Holiday(array1, name)
//String array1 = myLine.split(" ");
// check to make sure you have valid data
// String[] array2 = array1[1].split(" ");
System.out.println(array1[0]);
}
}
#Override
public int compareTo(Date o) {
// TODO Auto-generated method stub
return 0;
}
}
Pattern p = Pattern.compile("(.*?) (.*?) (\\(.*\\))");
Matcher m = p.matcher("20-01-01 Abs Def est (abcd)");
if (!m.matches()) throw new Exception("Invalid string");
String s1 = m.group(1); // 20-01-01
String s2 = m.group(2); // Abs Def est
String s3 = m.group(3); // (abcd)
Use a StringTokenizer, which has a " " as a delimiter by default.
You seem to be splitting based on whitespace. Each element of the string array would contain the individual whitespace-separate substrings, which you can then piece back together later on via string concatenation.
For instance,
array1[0] would be 20-01-01
array1[1] would be Abs
array1[2] would be Def
so on and so forth.
Another option is to Java regular expressions, but that may only be useful if your input text file is has a consistent formatting and if there's a lot of lines to process. It is very powerful, but requires some experience.
Match required text data by regular expression.
The regexp below ensure there are exactly 3 words in the middle and 1 word in the bracket.
String txt = "20-01-01 Abs Def est hhh (abcd)";
Pattern p = Pattern.compile("(\\d\\d-\\d\\d-\\d\\d) (\\w+ \\w+ \\w+) ([(](\\w)+[)])");
Matcher matcher = p.matcher(txt);
if (matcher.find()) {
String s1 = matcher.group(1);
String s2 = matcher.group(2);
String s3 = matcher.group(3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
However if you need more flexibility you may want to use code provided by Lence Java.

Categories