saurabh agarwal
saurabh agarwal

Reputation: 2184

Finding the sub string

I have string like

Strig foo = "PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something to be extracted]jdjdjdj"

I want output to be "something to be extracted" where regex of string is Principle*Teacher*Class*List[*]*.

After this make a new string

 Strig foo = "PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something new]jdjdjdj"

Upvotes: 1

Views: 125

Answers (2)

cнŝdk
cнŝdk

Reputation: 32145

If your String is always in the same format and contains the words Principle, Teachers and Class followed by [some text], then this is the Regex you need :

Principle\\w*Teachers\\w*Class\\w*\\[([\\s\\w]+)\\]\\w*

The matching group in \\[([\\s\\w]+)\\] will match the string you need.

Your code would be like this:

final String regex = "Principle\\w*Teachers\\w*Class\\w*\\[([\\s\\w]+)\\]\\w*";
final String string = "Strig foo = \"PrinciplexbxbxbxbxbxbTeachershshshshshhsClassdhdhdhhdhdhdList[something to be extracted]jdjdjdj\"\n";

string.replaceAll(regex, "something new");

Upvotes: 1

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60036

If you want to get something to be extracted then you can extract every thing between the two brackets \[(.*?)\], you can use Pattern like this :

String foo = ...;
String regex = "\\[(.*)\\]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(foo);

if (matcher.find()) {                                                
    System.out.println(matcher.group(1));
}

If you want to replace it you can use replaceAll with the same regex :

foo = foo.replaceAll("\\[.*?\\]", "[something new]");

regex demo

Upvotes: 1

Related Questions