Get Substring from a String from __ [duplicate] - java

This question already has answers here:
substring between two delimiters
(6 answers)
Closed 5 years ago.
I want to extract subString from a String, starting from __(Double UnderScore) till a "(Double Quotes) or special character '[](),' is found.
I have been at it for some while now but cannot figure it out.
For Example: Input String : "NAME":"__NAME"
Required String : __NAME
Thanks for your time.

You can use this regex (__(.*?))[\"\[\]\(\),] to get what you want you can use :
String str = "\"NAME\":\"__NAME\"";
String regex = "(__(.*?))[\"\\[\\]\\(\\),]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
__NAME
regex demo

You could try following code
String input="\"NAME\":\"__NAME\"";
int startIndex=input.indexOf("__");
int lastIndex=input.length();
String output=input.substring(startIndex, (lastIndex-1));
System.out.println(output);

May this solution help you:
import java.util.*;
class test
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String a=s.next();
int i=a.indexOf("__");
int j=a.indexOf('"',i);
System.out.println(a.substring(i,j));
}
}
In this firstly we calculate the index of __ and then we calculate the index of " after __.and then use substring method to get desired output.

Related

Finding the any number of characters between brackets using regex? [duplicate]

This question already has answers here:
Print regex matches in java
(2 answers)
Closed 3 years ago.
I've been struggling with some regex parsing to get a particular substring out of a string. I want to get the {0} out of a string. The caveat is that the substring can have any number of 0'
s within the {} and there can be many instances of {0} in the String. A few example inputs are:
{0} should print {0}
F-{000} print {000}
F-{00000000}-{0000} print {00000000} & {0000}
Here is the code I have:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
public static void main(String[] args) {
String displayFormat = "A-{0000}";
printValue("^\\{[0]+}$", displayFormat); // this searches for a string beginning with {, ends with }, and has 1 or more instances of 0 in it
printValue("\\{[0]+\\}", displayFormat); // same as above but without the strict requirement of beginning and ending with {}, rather looks for the literal {}
}
public static void printValue(String regex, String displayFormat) {
final Matcher matcher = Pattern.compile(regex).matcher(displayFormat);
String zeroSection = null;
while(matcher.find()) {
if(matcher.groupCount() > 0) {
System.out.println("Group: " + matcher.group(1));
}
}
}
}
Any help would be appreciated. Thanks!
I was able to find the correct regex. The regex that was posted in the answer above seems to work, but I guess the issue was more around how I was printing the string. I should have been printing group(0) instead of group(1). Silly mistake.

How could we search for an exact match for a word/ words in java using regex? These words could includes parenthesis, curly braces etc [duplicate]

This question already has answers here:
Regex whitespace word boundary
(3 answers)
Closed 3 years ago.
public static void main(String args[]) {
findExactWord find = new findExactWord();
String fullString = "reports of a chemical (reaction; in the kitchen) area found a male employee suffering from nausea";
System.out.println(find.isContainExactWord(fullString, "chemical (reaction; in the kitchen)"));
}
private boolean isContainExactWord(String fullString, String partWord){
String pattern = "\\b"+partWord+"\\b";
System.out.println("Pattern : "+partWord);
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(fullString);
return m.find();
}
I want this result to be - true.
Search input is : "chemical (reaction; in the kitchen)
this should search all characters exactly as is.
output is now : false
String pattern = partWord;
System.out.println("Pattern : " + partWord);
Pattern p = Pattern.compile(pattern, Pattern.LITERAL);
Matcher m = p.matcher(fullString);
return m.find();
now the tested version ;-)
it matches special characters and ignores newlines

Regex for Delimeter [duplicate]

This question already has answers here:
Is it possible to match nested brackets with a regex without using recursion or balancing groups?
(2 answers)
Closed 5 years ago.
I am trying to write a regex for delimiters “(“, “)”, “,”. I tried to write a regex but it is not the correct for the delimeters.
Let's say the input is mult(3,add(2,subs(4,3))). The output with my delimeter regex is: 3,add(2,subs(4,3.
public class Practice {
private static final String DELIMETER = "\\((.*?)\\)";
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String arg = reader.next();
Pattern p = Pattern.compile(DELIMETER);
Matcher m = p.matcher(arg);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
What is the correct regex to get string between the delimeters?
In general, you cannot use a regex to match anything which can nest recursively. However, if you removed the ? from your regex, it would match from the first ( to the last ), which might be good enough, depending on what you expect the input to look like.

How to extract sub strings containing multiple parentheses in Java? [duplicate]

This question already has answers here:
How to match string within parentheses (nested) in Java?
(2 answers)
Closed 6 years ago.
Is there a regex to extract sub strings from a string containing multiple parantheses?
For example my string is
String str = "(A(B(C(D(x)))))";
I want to print all the sub strings that lie within any pair of parantheses :
A(B(C(D(x))))
B(C(D(x)))
C(D(x))
D(x)
x
I tried using regex :
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
But this only extracts the sub string it finds between 1st pair of parentheses.
I have developed what you requested but not just with regex, but a recursive function. Please check following code:
public static void main(String[] args)
{
String str = "(A(B(C(D(x)))))";
findStuff(str);
}
public static void findStuff(String str){
String pattern = "\\((.+)\\)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
while (m.find())
{
String sub = m.group(1);
System.out.println(" Word: " + sub);
findStuff(sub);
}
}

remove all special characters in java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Replacing all non-alphanumeric characters with empty strings
import java.util.Scanner;
import java.util.regex.*;
public class io{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
String c;
if((c=scan.nextLine())!=null)
{
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find()){
c=c.replace(Character.toString(c.charAt(match.start())),"");
}
System.out.println(c);
}
}
}
Case 1
Input : hjdg$h&jk8^i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdgh&jk8^issh6
Case 2
Input : hjdgh&jk8i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdghjk8i0ssh6
Case 3
Input : hjdgh&j&k8i0ssh6
Expect : hjdghjk8i0ssh6
Output : hjdghjki0ssh6
Anyone please help me to figure out, what is wrong in my code logic ??
use [\\W+] or "[^a-zA-Z0-9]" as regex to match any special characters and also use String.replaceAll(regex, String) to replace the spl charecter with an empty string. remember as the first arg of String.replaceAll is a regex you have to escape it with a backslash to treat em as a literal charcter.
String c= "hjdg$h&jk8^i0ssh6";
Pattern pt = Pattern.compile("[^a-zA-Z0-9]");
Matcher match= pt.matcher(c);
while(match.find())
{
String s= match.group();
c=c.replaceAll("\\"+s, "");
}
System.out.println(c);
You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}
Your problem is that the indices returned by match.start() correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c every time, these indices become incorrect.
The best approach to solve this is to use replaceAll, for example:
System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));

Categories

Resources