I'm trying to split a string into different variables. Something like the opposite of String.format(). I want a particular regex to match and then that portion of the string should be assigned to a specific variable. Is that possible using StringReader or any other class?
Example my String is 5 13-DEC-2010 16:47 A Tach 220 380
now it should be assigned to variables like:
number = 5
date = 13-DEC-2010
time = 16:47
type = A Tach
num1 = 220
num2 = 380
where all variables can be strings
public static void main(String[] args) {
String s = "5 13-DEC-2010 16:47 A Tach 220 380";
String re = "(\\d+)\\s+(\\d{1,2}-[A-Z]{3}-\\d{4})\\s+(\\d{2}:\\d{2})\\s+([\\w\\s+]*)\\s+(\\d+)\\s+(\\d+)";
Pattern p = Pattern.compile(re);
String number=null,date=null,time=null,type=null,num1=null,num2=null;
Matcher m = p.matcher(s);
if (m.matches()) {
number = m.group(1);
date = m.group(2);
time = m.group(3);
type = m.group(4);
num1 = m.group(5);
num2 = m.group(6);
}
System.out.println(number);
System.out.println(date);
System.out.println(time);
System.out.println(type);
System.out.println(num1);
System.out.println(num2);
}
Try this:
var s = '5 13-DEC-2010 16:47 A Tach 220 380';
var re = /(\d+)\s+(\d{1,2}-[A-Z]{3}-\d{4})\s+(\d{2}:\d{2})\s+([\w\s+]*)\s+(\d+)\s+(\d+)/
var m = s.match(re);
Base from my past experience, there wasn't any builtin class that will do that. Just manually manipulate your data. Like split it (str.split("\s");), then stored in they respective variables. But the problem is the case "A Tach".
If you ask me I'll just replace the data seperator(in your case its a space) with a regex that will not occur in your string, something like ";=;" where your string will be transformed into
"5;=;13-DEC-2010;=;16:47;=;A Tach;=;220;=;380"
Then just split the data and parse it to their respective variable.
Related
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
I have a problem with String.format In android I want replace { 0 } with my id.
My this code not working:
String str = "abc&id={0}";
String result = String.format(str, "myId");
I think you should use replace method instead of format.
String str = "abc&id={0}";
str.replace("{0}","myId");
you have 2 ways to do that and you are mixing them :)
1.String format:
String str = "abc&id=%s";//note the format string appender %s
String result = String.format(str, "myId");
or
2.Message Format:
String str = "abc&id={0}"; // note the index here, in this case 0
String result = MessageFormat.format(str, "myId");
You have to set your integer value as a seperate variable.
String str = "abc&id";
int myId = 001;
String result = str+myId;
try this,
String result = String.format("abc&id=%s", "myId");
edit if you want more than one id,
String.format("abc&id=%s.id2=%s", "myId1", "myId2");
The syntax you're looking for is:
String str = "abc&id=%1$d";
String result = String.format(str, id);
$d because it's a decimal.
Other use case:
String.format("More %2$s for %1$s", "Steven", "coffee");
// ==> "More coffee for Steven"
which allows you to repeat an argument any number of times, at any position.
I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}
In debug mode I can see that locator of one of the element on the page is: By.name: NameOfMyElement_123.
The question is, how can I parse the following string (By.name: NameOfMyElement_123) in Java in order to have the type of my locator (name) and value (NameOfMyElement_123) ?
String[] split = "By.name: NameOfMyElement_123".split(" ");
or
Pattern p = Pattern.compile("([\\w.]*): ([\\w]*_[\\d]*)");
Matcher m = p.matcher("By.name: NameOfMyElement_123");
while (m.find()){
System.out.println(m.group(1));
System.out.println(m.group(2));
}
You could use split(). In this case, it's best to split with :
String[] splittedText = element.split(':');
String type = splittedText[0].trim();
String value = splittedText[1].trim();
Nothing fancy is necessary, two split() methods are enough:
String[] firstSplit = element.split(':');
String[] secondSplit = firstSplit[0].split('.');
String type = secondSplit[1].trim(); // will result in "name"
String value = firstSplit[1].trim(); // will result in "NameOfMyElement_123"
I have a string String a = "(3e4+2e2)sin(30)"; and i want to show it as a = "(3e4+2e2)*sin(30)";
I am not able to write a regular expression for this.
Try this replaceAll:
a = a.replaceAll("\) *(\\w+)", ")*$1");
You can go with this
String func = "sin";// or any function you want like cos.
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)]" + func, ")*siz");
System.out.println(a);
this should work
a = a.replaceAll("\\)(\\s)*([^*+/-])", ") * $2");
String input = "(3e4+2e2)sin(30)".replaceAll("(\\(.+?\\))(.+)", "$1*$2"); //(3e4+2e2)*sin(30)
Assuming the characters within the first parenthesis will always be in similar pattern, you can split this string into two at the position where you would like to insert the character and then form the final string by appending the first half of the string, new character and second half of the string.
string a = "(3e4+2e2)sin(30)";
string[] splitArray1 = Regex.Split(a, #"^\(\w+[+]\w+\)");
string[] splitArray2 = Regex.Split(a, #"\w+\([0-9]+\)$");
string updatedInput = splitArray2[0] + "*" + splitArray1[1];
Console.WriteLine("Input = {0} Output = {1}", a, updatedInput);
I did not try but the following should work
String a = "(3e4+2e2)sin(30)";
a = a.replaceAll("[)](\\w+)", ")*$1");
System.out.println(a);