I need to replace quotes in following string.
String str = "This is 'test()ing' and test()ing'";
Final output should be "This is test()ing and test()ing'";
i.e replace only if it starts with 'test() and ends with '. Text in between remains the same.
This one is not working.
str = str.replaceAll("^('test())(.*)(')$", "test()$2");
Please suggest suitable regex for the same.
This regular expression will have the desired outcome:
str = str.replaceAll("'test\\(\\)(.*?)'", "test()$1");
with .*? the string is matched lazily and doesn't match to the end of the whole string.
You can use:
str = str.replaceAll("'(test\\(\\)[^']*)'", "$1");
RegEx Demo
Doesn't look like you actually want to have the ^ and $ anchors (start/end of line) in your regex.
Aside from that, it will consume more than you want. If you want the .* to stop at the earliest point it can continue, you should make it match reluctantly, like .*?.
So your regex would be:
('test\(\))(.*?)(')
Make the middle part non greedy:
(')(.*?)(')
i.e.
str = str.replaceAll("(')(.*?)(')", "$2");
and if it should always start with test(), add
str = str.replaceAll("(')(test().*?)(')", "$2");
Check this example and this one.
Related
How to get ricCode:.ABC from following string.
My matcher is
Matcher matcher = Pattern.compile("ricCode:([A-Za-z]+),$").matcher(str);
String str = "{AMX:{ricCode:.ABC,indexDetailEnable:true,price:20,648.15,netChange:<spanclass="md-down">-41.09</span>,percentChange:<spanclass="md-down">-0.20%</span>,tradeDate:17/04/05,tradeTime:16:40,chartDate:17/04/05,chartTime:16:40}";
What is missing in the regex?
Change your regex from this:
ricCode:([A-Za-z]+),$
to this:
ricCode:([A-Za-z.]+)(?=,)
Your original regex would only allow alphabetic characters after ricCode:, but your example has a period . character. Also you were matching the , character, but this would also include the comma in your match, you dont want this - so I added a positive lookahead for the comma so it looks for it there but does not match it. Finally you had the $ character at the end of your regex which matches the end of the string, you dont want to look for the end of the string immediately after the comma, so I removed it.
It helps to use regexr.com to test out your expression.
I have strings like
#lle #mme: #crazy #upallnight:
I would like to remove the words which starts with either # or #. It works perfectly fine if those words doesn't contain the ':' character. However, that ':' character is left whenever I delete the words. Therefore I decided to replace those ':' characters before I delete the words using a string.replace() function. However, they are still not removed.
String example = "#lle #mme: #crazy #upallnight:";
example.replace(':',' ');
The result : #lle #mme: #crazy #upallnight:
I am pretty stuck here, anyhelp would be appreciated.
You can do this:
example = example.replaceAll(" +[##][^ ]+", "");
What this will do is replace any substrings in your string that match the regex pattern [##][^ ]+ with the empty string. Since that pattern matches the words you want to dump, it'll do what you want.
Demo of the pattern on Regex101
From Java docs:
String s = "Abc: abc#:";
String result = s.replace(':',' ');
Output in variable result= Abc abc#
I think you forgot to store the returned result of replace() method in some other String variable.
I am looking for a regular expression that can strip all 'a' characters from the beginning of an input word (comprising only of English alphabet).
How would I do this using an regular expression?
The following look behind based regex fails to do the job:
(?<=a*?)(\w)+
as for input abc the above regular expression would return abc.
Is there a clean way to do this using lookbehinds?
A (brute force-ish) regular expression that does work is using negation:
(?<=a*)([[^a]&&\w])*
which returns the correct answer of bc for an input word abc.
But I was wondering if there could be a more elegant regular expression, say, using the correct quantifier?
Pattern removeWords = Pattern.compile("\\b(?:a)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher fix = removeWords.matcher(YourWord);
String fixedString = fix.replaceAll("");
this will remove a from the current string and if you want to remove some other letters
Pattern removeWords = Pattern.compile("\\b(?:a|b|c)\\b\\s*",Pattern.CASE_INSENSITIVE);
you ca do it this way
I think that a regex for this problem is overkill.
You could instead do:
str = str.startsWith("a") ? str.substring(1) : str;
Try with:
(?i)\\ba?(\\w+)\\b
and replace a word with captured group 1.
Code example:
String word = "aWord Another";
word = word.replaceAll("(?i)\\ba?(\\w+)\\b", "$1");
System.out.println(word);
with output:
Word nother
There are much more simpler way to do this, but as you insist on using using lookbehinds, I will give one. The regex will be
(?<=\b)a+(\w*)
Regex Breakdown
(?<=\b) #Find all word boundaries
a+ #Match the character a literally at least once. We have already ensured using word boundary to find those a's only which are starting of word
(\w*) #Find remaining characters
Regex Demo
Java Code
String str = "abc cdavbvhsza aaabcd";
System.out.println(str.replaceAll("(?<=\\b)a+(\\w*)", "$1"));
Ideone Demo
I have a string here:
javax.swing.JLabel[,380,30,150x25,alignmentX=0.0,alignmentY=0.0]: Hello
I want to remove everything before the ":", including the ":" itself. This would leave only "Hello". I read about regex, but no combination I tried worked. Can someone tell me how to do it. Thanks in advance!
You need to use replaceAll method or replaceFirst.
string.replaceFirst(".*:\\s*", "");
or
string.replaceAll(".*:\\s*", "");
This would give you only Hello. If you remove \\s* pattern,then it would give you <space>Hello string.
.* Matches any character zero or more times, greedily.
: Upto the colon.
\\s* Matches zero or more space characters.
You could also just split the string by : and take the second string. Like this
String sample = "javax.swing.JLabel[,380,30,150x25,alignmentX=0.0,alignmentY=0.0]: Hello";
System.out.println(sample.split(":", -1)[1]);
This will output
<space>Hello
If you want to get rid of that leading space just trim it off like
System.out.println(sample.split(":", -1)[1].trim());
Regular expression to obtain value from [[text]]. I have tried the regex
"((?<=[[)*(?=]])*)+" the value between [[ ]] is not obtained.
For example, from the string [[text]], we should obtain text.
Pattern pat = Pattern.compile("((?<=\\[[)*(?=\\]])*)");
Matcher matcher = pat.matcher("[[text]]");
String next ="";
while(matcher.find()) {
next = matcher.group(0);
break;
}
System.out.println(next); //next should be text
You need to escape brackets [] when using them as actual characters in a regular expression. And you also need to add something to actually capture what is between the brackets. You can use .* for that or use my approach, if you are sure the value cannot contain a ].
((?<=\[\[)([^\]]*)(?=\]\]))+
There is not even really a need to use lookbacks und lookaheads unless you explictly need to exempt those limiters from the match. This will work just as well:
\[\[([\]]*\]\]
And obviously when you put these into a String, you need to add additional \ to escape the \ for the String...they are just more readable this way.
If you don't wanna get into regex, String.replaceAll can also help you.
String s2 = s.replaceAll("\\[", "").replaceAll("\\]", "");
"(?<=\\[\\[)[^\\]]*"
this should work for you