Removing text from string starting and ending with special chracter - java

i have a string like "Hi ${CUSTOMER_NAME} your address is ${CUSTOMER_ADDRESS}
".
I need to remove every text which starts with $and ends with }. so the output of above should be like Hi Your address is.

In this case you should use regex, here is an example you can use:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String regex = "(\\$\\{\\w+\\})";
String str = "Hi ${CUSTOMER_NAME} your address is ${CUSTOMER_ADDRESS}";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(str);
String replaceAll = matcher.replaceAll("");
System.out.println(str);
System.out.println(replaceAll);
}
}
You are welcome to read more about regex and metcher.
Hope this helps

Related

Regex pattern in Java to replace everything except certain sequence of tokens

I need to make a method that will retrieve words from the text without anything (punctuation etc.) except lowercase words themselves.
BUT I've struggled for 2 hours with regex pattern and faced such a problem.
There are words like "50-year" in the text.
And with my regex, output will be like:
-year
Instead of a normal
year
But I cannot replace dash symbol "-" cause there is another words with hyphen that should be left.
Here is a code:
public List<String> retrieveWordsFromFile() {
List<String> wordsFromText = new ArrayList<>();
scanner.useDelimiter("\\n+|\\s+|'");
while (scanner.hasNext()) {
wordsFromText.add(scanner.next()
.toLowerCase()
.replaceAll("^s$", "is")
.replaceAll("[^\\p{Lower}\\-]", "")
);
}
wordsFromText.removeIf(word -> word.equals(""));
return wordsFromText;
}
So how can I say that I need to replace everything except text and words with dash starting only with a letter/s. So this regex string should probably be such a "merged" into one sequence?
Use the regex, \\b[\\p{Lower}]+\\-[\\p{Lower}]+\\b|\\b[\\p{Lower}]+\\b
Demo:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "Hello world", "Hello world 123", "HELLO world", "50-year", "stack-overflow" };
// Define regex pattern
Pattern pattern = Pattern.compile("\\b[\\p{Lower}]+\\-[\\p{Lower}]+\\b|\\b[\\p{Lower}]+\\b");
for (String s : arr) {
// The string to be matched
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
// Matched string
String matchedStr = matcher.group();
// Display the matched string
System.out.println(matchedStr);
}
}
}
}
Output:
world
world
world
year
stack-overflow
Explanation of regex:
\b species the word boundary.
+ specifies one or more characters.
| specifies OR
This is how you can discard the non-matching text:
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "Hello world", "Hello world 123", "HELLO world", "50-year", "stack-overflow", "HELLO",
"HELLO WORLD", "&^*%", "hello", "123", "1w23" };
// Regex pattern
String regex = ".*?(\\b[\\p{Lower}]+\\-[\\p{Lower}]+\\b|\\b[\\p{Lower}]+\\b).*";
for (String s : arr) {
// Replace the string with group(1)
String str = s.replaceAll(regex, "$1");
// If the replaced string does not match the regex pattern, replace it with
// empty string
s = !str.matches(regex) ? "" : str;
// Display the replaced string if it is not empty
if (!s.isEmpty()) {
System.out.println(s);
}
}
}
}
Output:
world
world
world
year
stack-overflow
hello
Explanation of replacement:
.*? matches everything reluctantly i.e. before it yields to the next pattern.
s.replaceAll(regex, "$1") will replace s with group(1)

Remove double quotes from output Java

I am trying to extract a url from the string. But I am unable to skip the double quotes in the output.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String s1 = "<a id=\"BUTTON_LINK\" style=\"%%BUTTON_LINK%%\" target=\"_blank\" href=\"https://||domainName||/basketReviewPageLoadAction.do\">%%CHECKOUT%%</a>";
//System.out.println(s1);
Pattern pattern = Pattern.compile("\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))");
Matcher matcher = pattern.matcher(s1);
if(matcher.find()){
String url = matcher.group(1);
System.out.println(url);
}
}
}
My Output is:
"https://||domainName||/basketReviewPageLoadAction.do"
Expected Output is:
https://||domainName||/basketReviewPageLoadAction.do
I cannot do string replace. I have add few get param in this output and attach back it to original string.
Regex: (?<=href=")([^\"]*) Substitution: $1?params...
Details:
(?<=) Positive Lookbehind
() Capturing group
[^] Match a single character not present in the list
* Matches between zero and unlimited times
$1 Group 1.
Java code:
By using function replaceAll you can add your params ?abc=12 to the end of the capturing group $1 in this case href.
String text = "<a id=\"BUTTON_LINK\" style=\"%%BUTTON_LINK%%\" target=\"_blank\" href=\"https://||domainName||/basketReviewPageLoadAction.do\">%%CHECKOUT%%</a>";
text = text.replaceAll("(?<=href=\")([^\"]*)", String.format("$1%s", "?abc=12"));
System.out.print(text);
Output:
<a id="BUTTON_LINK" style="%%BUTTON_LINK%%" target="_blank" href="https://||domainName||/basketReviewPageLoadAction.do?abc=12">%%CHECKOUT%%</a>
Code demo
You can try one of these options:
System.out.println(url.replaceAll("^\"|\"$", ""));
System.out.println(url.substring(1, url.length()-1));
ugly, seems works.Hope this help.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
String s1 = "<a id=\"BUTTON_LINK\" style=\"%%BUTTON_LINK%%\" target=\"_blank\" href= \"https://||domainName||/basketReviewPageLoadAction.do\">%%CHECKOUT%%</a>";
//System.out.println(s1);
Pattern pattern = Pattern.compile("\\s*(?i)href\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^'\">\\s]+))");
Matcher matcher = pattern.matcher(s1);
if (matcher.find()) {
String url = Stream.of(matcher.group(2), matcher.group(3),
matcher.group(4)).filter(s -> s != null).collect(Collectors.joining());
System.out.print(url);
}
}
}
This solution worked for now.
Pattern pattern = Pattern.compile("\\s*(?i)href\\s*=\\s*\"([^\"]*)");
You will try this out,
s1 = s1.Replace("\"", "");

How to preserve delimeters while using String.split() in Java?

String TextValue = "hello{MyVar} Discover {MyVar2} {MyVar3}";
String[] splitString = TextValue.split("\\{*\\}");
What I'm getting output is [{MyVar, {MyVar2, {MyVar3] in splitString
But my requirement is to preserve those delimiters {} i.e. [{MyVar}, {MyVar2}, {MyVar3}].
Required a way to match above output.
Use something like so:
Pattern p = Pattern.compile("(\\{\\w+\\})");
String str = ...
Matcher m = p.matcher(str);
while(m.find())
System.out.println(m.group(1));
Note, the code above is untested but that will look for words within curly brackets and place them in a group. It will then go over the string and output any string which matches the expression above.
An example of the regular expression is available here.
Thanks kelvin & npinti.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CreateMatcherExample {
public static void main(String[] args) {
String TextValue = "hello{MyVar} Discover {My_Var2} {My_Var3}";
String patternString = "\\{\\w+\\}";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(TextValue);
while(matcher.find()) {
System.out.println(matcher.group());
}
}
}

Unable to Parse reqular expression in JAVA

This is my code,
String xyz = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}], [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
String pattern = ".*],\\s*\\[.*";//"(.*)(],\\s.*\\[)(.*)";
Pattern p1 = Pattern.compile(pattern);
Matcher m1 = p1.matcher(xyz);
boolean b = m1.matches();
System.out.println(b);
I would like to replace pattern '], [' with "".
I used replaceAll but no luck
Check it in working Fiddle
Use the regex as below
String pattern = "\],[ ]*\[";
xyz =xyz.replaceAll("]\s*,\s*\[", "],[");
This worked like charm and also this link helped me alot http://regexr.com/
Thank you for all your inputs!
The output of this block is: {"status":"ok","data":[{"RatingCount":4}{"RatingCount":1}{"RatingCount":1}]"code":1}
public static void main(String[] args) {
String str = "{\"status\":\"ok\",\"data\":[{\"RatingCount\":4}], [{\"RatingCount\":1}], [{\"RatingCount\":1}]\"code\":1}";
System.out.println(replace(str, "\\],\\s+\\["));
}
public static String replace(String str, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.replaceAll("");
}

Regex after a special character in Java

I am using regex in java to get a specific output from a list of rooms at my University.
A outtake from the list looks like this:
(A55:G260) Laboratorium 260
(A55:G292) Grupperom 292
(A55:G316) Grupperom 316
(A55:G366) Grupperom 366
(HDS:FLØYEN) Fløyen (appendix)
(ODO:PC-STUE) Pulpakammeret (PC-stue)
(SALEM:KONF) Konferanserom
I want to get the value that comes between the colon and the parenthesis.
The regex I am using at the moment is:
pattern = Pattern.compile("[:]([A-Za-z0-9ÆØÅæøå-]+)");
matcher = pattern.matcher(room.text());
I've included ÆØÅ, because some of the rooms have Norwegian letters in them.
Unfortunately the regex includes the building code also (e.g. "A55") in the output... Comes out like this:
A55
A55
A55
:G260
:G292
:G316
Any ideas on how to solve this?
The problem is not your regular expression. You need to reference group(1) for the match result.
while (matcher.find()) {
System.out.println(matcher.group(1));
}
However, you may consider using a negated character class instead.
pattern = Pattern.compile(":([^)]+)");
You can try a regex like this :
public static void main(String[] args) {
String s = "(HDS:FLØYEN) Fløyen (appendix)";
// select everything after ":" upto the first ")" and replace the entire regex with the selcted data
System.out.println(s.replaceAll(".*?:(.*?)\\).*", "$1"));
String s1 = "ODO:PC-STUE) Pulpakammeret (PC-stue)";
System.out.println(s1.replaceAll(".*?:(.*?)\\).*", "$1"));
}
O/P :
FLØYEN
PC-STUE
Can try with String Opreations as follows,
String val = "(HDS:FLØYEN) Fløyen (appendix)";
if(val.contains(":")){
String valSub = val.split("\\s")[0];
System.out.println(valSub);
valSub = valSub.substring(1, valSub.length()-1);
String valA = valSub.split(":")[0];
String valB = valSub.split(":")[1];
System.out.println(valA);
System.out.println(valB);
}
Output :
(HDS:FLØYEN)
HDS
FLØYEN
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class test
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "(HDS:FLØYEN) Fløyen (appendix)";
String pattern = ":([^)]+)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println(m.group(1));
}
}
}

Categories

Resources