Most efficient way to get the substring after a specific other substring - java

If I have a string that looks something like this:
String text = "id=2009,name=Susie,city=Berlin,phone=0723178,birthday=1991-12-07";
I only want to have the info name and phone. I know how to parse the entire String, but in my specific case it is important to only get those two "fields".
So what is the best/most efficient way to have my search method do the following:
search for the substring "name=" and return the substring after it ("Susie") until it reaches the next comma
My approach would have been to:
get the last index of "name=" first
use this index then as the new start for my parsing method
Any other suggestions maybe on how this could be done more efficiently and with a more condense code? Thank you for any input

You can use following regex to capture the expected word after phone and name and get frist group from matched object:
(?:phone|name)=([^,]+)
With regards to following command if it might happen to have a word which is contain phone or name as a more comprehensive way you can putt a comma before your name.
(?:^|,)(?:phone|name)=([^,]+)
Read more about regular expression http://www.regular-expressions.info/

Regex might be more efficient, but for readability, I <3 Guava
String text = "id=2009,name=Susie,city=Berlin,phone=0723178,birthday=1991-12-07";
final Map<String, String> infoMap = Splitter.on(",")
.omitEmptyStrings()
.trimResults()
.withKeyValueSeparator("=")
.split(text);
System.out.println(infoMap.get("name"));
System.out.println(infoMap.get("birthday"));

Related

Java remove dynamic substring from string

I need to remove dynamic substring from string. There is a few similar topic of this theme, but noone of them helped me. I have a string e.g.:
product test1="001" test2="abc" test3="123xzy"
and i need output:
product test1="001" test3="123xzy"
I mean I need remove test2="abc". test2 is an unique element and can be placed anywhere in original string. "abc" is dynamic variable and can have various length. What is the fastest and the most elegant solution of this problem? Thx
You can use a regular expression:
String input = "product test1=\"001\" test2=\"abc\" test3=\"123xzy\"";
String result = input.replaceAll("test2=\".*?\"\\s+", "");
In substance: find a substring like test2="xxxxxx", optionally followed by some spaces (\\s+) and replace it with nothing.

Java regex: Replacing dynamic substrings

Suppose I have a String containing static tags that looks like this:
mystring = "[tag]some text[/tag] untagged text [tag]some more text[/tag]"
I want to remove everything between each tag pair. I've figured out how to do so by using the following regex:
mystring = mystring.replaceAll("(?<=\\[tag])(.*?)(?=\\[/tag])", "");
The result of which will be:
mystring = "[tag][/tag] untagged text [tag][/tag]"
However, I'm unsure how to accomplish the same goal if the opening tag is dynamic. Example:
mystring = "[tag parameter="123"]some text[/tag] untagged text [tag parameter="456"]some more text[/tag]"
The "value" of the parameter portion of the tag is dynamic. Somehow, I have to introduce a wildcard to my current regex, but I am unsure how to do this.
Essentially, replace the contents of all pairings of "[tag*]" and "[/tag]" with empty string.
An obvious solution would be to do something like this:
mystring = mystring.replaceAll("(?<=\\[tag)(.*?)(?=\\[/tag])", "");
However, I feel like that would be hacking around the problem because I'm not really capturing a full tag.
Could anyone provide me with a solution to this problem? Thanks!
I guess I've got it.
I thought long and hard about what #AshishMathew said, and yeah, lookbehinds can't have unfixed, lengths, but maybe instead of replacing it with nothing, we add a ] to it, like so:
mystring = mystring.replaceAll("(?<=\\[tag)(.*?)(?=\\[/tag])", "]");
(?<=\\[tag) is the look-behind which matches [tag
(.*?) is all the code between [tag and [/tag], which may even be the parameters of the tag, all of which is replaced by a ]
When I tried this code by replacing the match with "", I got [tag[/tag] untagged text [tag[/tag] as the output. Hence, by replacing the match with a ] instead of nothing, you get the (hopefully) desired output.
So this is my lazy solution (pardon the regex pun) to the problem.
I suggest matching the whole tag with content and replacing with the opening/closing tags without content :
mystring.replaceAll("\\[tag[^\\]]*\\][^\\[]*\\[/tag]", "[tag][/tag]")
Ideone test.
Note that I didn't bother conserving the tag attributes since you mentionned in another answer's comments that you didn't need them, but they could be kept by using a capturing group.

Regex to extract value from link

I have a String like file:///android_asset/GwyXUyisyq. I want to extract the GwyXUyisyq from the rest of the string. The value will change in every instance, but the file:///android_asset/ will always remain fixed. What regex can I use to achieve the same?
You don't need a regex here :
Just find the last index of / and replace everything before it :)
String s = "file:///android_asset/GwyXUyisyq";
System.out.println(s.replace(s.substring(0,s.lastIndexOf("/")+1), ""));
O/P :GwyXUyisyq

How to extract substrings from a string in java

I am not so confident in Java so I need some help to extract multiple substrings from a string.string is as given below.
I have a text file with possibly thousands of similar POS-tagged lines that I need to extract the original text from that.I have tried using tokenizer but didn't really get the result I wanted.I tried using Pattern Matcher and I am having problems with the regex.
String="I_PRP recently_RB purchased_VBD this_DT camera_NN";
I want to get the output= I recently purchased this camera.
I use
Regex: [\/](.*?)\s\b
But its not working.Please help me.
try
String s= "I_PRP recently_RB purchased_VBD this_DT camera_NN";
s = s.replaceAll("_\\w+(?=(\\s|$))", "");
System.out.println(s);
prints
I recently purchased this camera
It seems that you are attaching a tag to indicate the word type (e.g. noun, verb or pronoun) if this suffix will be always capital letters, it is more safe to use the following regex in your replaceAll
s = s.replaceAll("_[A-Z]+(?=(\\s|$))", "");

A question on swapping XML attributes within a tag in Java

the question sounds a bit confusing, but it is actually straightforward. This is a follow-up of my previous post:
Need a little help on this regular expression
after successful transformation of the String, now the String looks like:
<media id="pc011018" rights="licensed"
type="photo">
<title>Sri Lankans harvest tea</title>
Now the only task left is to swap the three attributes of media node, so the output String should be:
<media type="photo" id="pc011018" rights="licensed">
<title>Sri Lankans harvest tea</title>
I actually could think of a way of doing this: first of all, I extract the string enclosed by the first pair of "[" bracket. Then for this string, I will use a StringTokenizer to tokenize three attributes strings: type, id, rights; then rearrange them in a StringBuffer,turn it back into a string, then finally concatenate with the remaining [title] substring.
I am just wondering if there is a better and more efficient way rather than using StringToknizer? Please kindly help, thanks.
A real hacky way of doing this
String input="<media id=\"pc011018\" rights=\"licensed\" type=\"photo\"><title>Sri Lankans harvest tea</title></media>";
Pattern r= Pattern.compile("<media id=\"(.*)\" rights=\"(.*)\" type=\"(.*)\">(.*)");
Matcher m = r.matcher(input);
m.find();
System.out.println("<media type=\""+m.group(3)+ "\" + id=\""+ m.group(1) + "\" rights=\"" + m.group(2) + "\">"+m.group(4));
Will only work if the data is always as you describe

Categories