Why does Java put a string before a word and not after?
from the String value you want to get the word before and after <in>
String ref = "application<in>rid and test<in>efd";
int result = ref.indexOf("<in>");
int result1 = ref.lastIndexOf("<in>");
String firstWord = ref.substring(0, result);
String[] wor = ref.split("<in>");
for (int i = 0; i < wor.length; i++) {
System.out.println(wor[i]);
}
}
my expected result
String[] output ={application,rid,test,efd}
i tried with 2 options first one IndexOf
, but if the row has more than two <in>
i, i don't get the expected Second One result split
, also not getting with my expected output
suggest the best way to get the word (before and after <in>
)
source to share
You can use an expression like this: \b([^ ]+?)<in>([^ ]+?)\b
(example here ). This should match the line before and after the tag <in>
and put them in two groups.
So, given this:
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\b([^ ]+?)<in>([^ ]+?)\\b");
Matcher m = p.matcher(ref);
while(m.find())
System.out.println("Prior: " + m.group(1) + " After: " + m.group(2));
Productivity:
Prior: application After: rid
Prior: test After: efd
Alternatively used split
:
String[] phrases = ref.split("\\s+");
for(String s : phrases)
if(s.contains("<in>"))
{
String[] split = s.split("<in>");
for(String t : split)
System.out.println(t);
}
Productivity:
application
rid
test
efd
source to share
Regex is your friend :)
public static void main(String args[]) throws Exception {
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\w+(?=<in>)|(?<=<in>)\\w+");
Matcher m = p.matcher(ref);
while (m.find()) {
System.out.println(m.group());
}
}
O / P:
application
rid
test
efd
source to share
Surely matching what you want with the Pattern/Matcher
API is easier for this problem.
However, if you are looking for a quick and quick solution String#split
, then you may want to consider:
String ref = "application<in>rid and test<in>efd";
String[] toks = ref.split("<in>|\\s+.*?(?=\\b\\w+<in>)");
Output:
application
rid
test
efd
This regex is split into <in>
or pattern matching a space, followed by 0 more characters, followed by the word and <in>
.
source to share