Java Json String extract number and replace specific text - java

I have a text file in json, and I want to replace NumberInt(x) with the number x.
In the text file, there are records/data which is in json that has a field workYear: NumberInt(2010) as an example.
I want to replace this into workYear: 2010 by removing NumberInt( and ).
This NumberInt(x) is located anywhere in text file and I want to replace all of it with its number.
I can search all the occurences of this, but I am not sure how to replace it with just the number value.
String json = <json-file-content>
String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);
while (matcher.find()) {
String s = matcher.group(0);
int workYear = Integer.parseInt(s.replaceAll("[^0-9]", ""));
System.out.println(workYear);
}
I would like to replace all the NumberInt(x) with just the number value int json String... then I will update the text file (json file).
Thanks!

Following should work. You need to capture the tokens.
String json = "workYear:NumberInt(2010) workYear:NumberInt(2011)";
String sPattern = "NumberInt\\(([0-9]+)\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);
List<String> numbers = new ArrayList<>();
while (matcher.find()) {
String s = matcher.group(1);
numbers.add(s);
}
for (String number: numbers) {
json = json.replaceAll(String.format("NumberInt\\(%s\\)", number), number);
}
System.out.println(json);

You could build the output using a StringBuilder like below,
Please refer to JavaDoc for appendReplacement for info on how this works.
String s = "workYear: NumberInt(2010)\nworkYear: NumberInt(2012)";
String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(s);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
String s2 = matcher.group(0);
int workYear = Integer.parseInt(s2.replaceAll("[^0-9]", ""));
matcher.appendReplacement(sb, String.valueOf(workYear));
}
matcher.appendTail(sb);
String result = sb.toString();

Related

How can i extract substring from the string using regex in Java?

I have a String xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx Now, I want to extract substrings slm/attachment/63338424306/Note.jpg & Note.jpg from the String in to variables i.e. temp1 & temp2.
How can I do that using regex in Java?
Note: 63338424306 could be any random no. & Note.jpg could be anything
like Note.png or abc.jpg or xxxx.yyy etc.
Please help me to extract these two strings using regex.
You can use negative look behind to get file name
((?:.(?<!/))+)\"
and below regex to get full path
/(.*)\"
Sample code
public static void main(String[] args) {
Pattern pattern = Pattern.compile("/(.*)\"");
Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
Matcher matcher = pattern.matcher(matchString);
String fullString = "";
while (matcher.find()) {
fullString = matcher.group(1);
}
matcher = pattern1.matcher(matchString);
String fileName = "";
while (matcher.find()) {
fileName = matcher.group(1);
}
System.out.println(fullString + " " + fileName);
}
As per your comment taking the string as declared below in my code:
Please clarify if your input string is not like this or I'm missing something.
public static void main(String[] args) {
String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
String url = null;
// The below pattern will grab string between quotes
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
url = m.group(1);
}
// and this will grab filename from the path(url)
p = Pattern.compile("(?:.(?<!/))+$");
m = p.matcher(url);
while (m.find()) {
System.out.println(m.group());
}
}

Match everything after and before something regex Java

Here is my code:
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern
Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch
String store= "";
// print match and store match in String Store
if (m.find())
{
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
//repeat the process
Pattern p1 = Pattern.compile("(.*)[^\\/]");
Matcher m1 = p1.matcher(store);
if (m1.find())
{
String theGroup = m1.group(0);
System.out.format("'%s'\n", theGroup);
}
I want to to match everything that is after excludethis and before a / that comes after.
With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.
Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.
Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,
(?<=.com/excludethis).*(?=/)
Also, in Java you don't need to escape /
Your modified code,
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch
String store = "";
// print match and store match in String Store
if (m.find()) {
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
System.out.println("Store: " + store);
Prints,
'123456'
Store: 123456
Like you wanted to capture the value.
This may be useful for you :)
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
If you don't want to use regex, you could just try with String::substring*
String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));
Output:
123456
* Definitely don't actually use this

how can I get particular string(sub string ) from a string

I have string like
{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}
{Imapact}{assest}{custom_23_multiplication}.
From this I want only those sub string which contains "custom".
For example from above string I want only
{Custom_21_addtion}{custom_22_substration}{custom_23_multiplication}.
How can I get this?
You can use a regular expression, looking from {custom to }. It will look like this:
Pattern pattern = Pattern.compile("\\{custom.*?\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
System.out.print(matcher.group());
}
The .* after custom means 0 or more characters after the word "custom", and the question mark limits the regex to as few character as possible, meaning that it will break on the next } that it can find.
If you want an alternative solution without regex:
String a = "{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}{custom_23_multiplication}";
String[] b = a.split("}");
StringBuilder result = new StringBuilder();
for(String c : b) {
// if you want case sensitivity, drop the toLowerCase()
if(c.toLowerCase().contains("custom"))
result.append(c).append("}");
}
System.out.println(result.toString());
you can do it sth like this:
StringTokenizer st = new StringTokenizer(yourString, "{");
List<String> llista = new ArrayList<String>():
Pattern pattern = Pattern.compile("(\W|^)custom(\W|$)", Pattern.CASE_INSENSITIVE);
while(st.hasMoreTokens()) {
String string = st.nextElement();
Matcher matcher = pattern.matcher(string);
if(matcher.find()){
llista.add(string);
}
}
Another solution:
String inputString = "{Action}{RequestId}{Custom}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}" ;
String strTokens[] = inputString.split("\\}");
for(String str: strTokens){
Pattern pattern = Pattern.compile( "custom", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
System.out.println("Tag Name:" + str.replace("{",""));
}
}

Regular expression to transform SQL format to java format

I'm trying with no chance to transform sql attributes to java format.
Let's have an example: I want to change: "p_start_date" to "pStartSate".
I've tried to use
String var = "p_start_date";
var.replaceAll("(_[a-z])\1", "([A-Z])\1");
and also
Pattern pattern = Pattern.compile("([a-z0-9]+_)*");
Matcher matcher = pattern.matcher(var);
if (matcher.find()) {
// Get all groups for this match
//System.out.println(matcher.groupCount());
for (int i=0; i<=matcher.groupCount(); i++) {
String groupStr = matcher.group(i);
System.out.println(groupStr);
}
}
But both doesn't work
Is this what you are looking for?
String var = "p_start_date";
Pattern pattern = Pattern.compile("_([a-z])");
Matcher matcher = pattern.matcher(var);
StringBuffer sb=new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
System.out.println(sb);
output: pStartDate

Parsing String in Java using a Pattern

I am trying parse out 3 pieces of information from a String.
Here is my code:
text = "H:7 E:7 P:10";
String pattern = "[HEP]:";
Pattern p = Pattern.compile(pattern);
String[] attr = p.split(text);
I would like it to return:
String[0] = "7"
String[1] = "7"
String[2] = "10"
But all I am getting is:
String[0] = ""
String[1] = "7 "
String[2] = "7 "
String[3] = "10"
Any suggestions?
A not-so-elegant solution I just devised:
String text = "H:7 E:7 P:10";
String pattern = "[HEP]:";
text = text.replaceAll(pattern, "");
String[] attr = text.split(" ");
From the javadoc, http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#split(java.lang.CharSequence) :
The array returned by this method contains each substring of the input
sequence that is terminated by another subsequence that matches this
pattern or is terminated by the end of the input sequence.
You get the empty string first because you have a match at the beginning of the string, it seems.
If I try your code with String text = "A H:7 E:7 P:10" I get indeed:
A 7 7 10
Hope it helps.
I would write a full regular expression like the following:
Pattern pattern = Pattern.compile("H:(\\d+)\\sE:(\\d+)\\sP:(\\d+)");
Matcher matcher = pattern.matcher("H:7 E:7 P:10");
if (!matcher.matches()) {
// What to do!!??
}
String hValue = matcher.group(1);
String eValue = matcher.group(2);
String pValue = matcher.group(3);
Basing on your comment I take it that you only want to get the numbers from that string (in a particular order?).
So I would recommend something like this:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("H:7 E:7 P:10");
while(m.find()) {
System.out.println(m.group());
}

Categories