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>

)

+3


source to share


4 answers


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

      

+4


source


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

      

+2


source


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

      

Demo version of RegEx

This regex is split into <in>

or pattern matching a space, followed by 0 more characters, followed by the word and <in>

.

+1


source


You can also try the below code, it is quite simple

class StringReplace1
{
    public static void main(String args[])
    {
        String ref = "application<in>rid and test<in>efd";

        System.out.println((ref.replaceAll("<in>", " ")).replaceAll(" and "," "));
        }
}

      

0


source







All Articles