How split a [0] like words from string using regex pattern.0 can replace any integer number.
I used regex pattern,
private static final String REGEX = "[\\d]";
But it returns string with [.
Spliting Code
Pattern p=Pattern.compile(REGEX);
String items[] = p.split(lure_value_save[0]);
You have to escape the brackets:
String REGEX = "\\[\\d+\\]";
Java doesn't offer an elegant solution to extract the numbers. This is the way to go:
Pattern p = Pattern.compile(REGEX);
String test = "[0],[1],[2]";
Matcher m = p.matcher(test);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
Related
Hi I have some string like this:
location/city/home-a-berlin?/someNewAdress
I want to extract word berlin which placed between "-a-" and "?". How can i do that with regex in java?
I can do it by using string API but kinda stuck with regex.
String cityName = url.substring(url.lastIndexOf("-a-")+3, url.indexOf('?')) //berlin
You can use a capture group with a negated character class.
-a-([^\?]+)\?
Regex demo | Java demo
In Java:
String regex = "-a-([^\\?]+)\\?";
String string = "location/city/home-a-berlin?/someNewAdress\n";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
berlin
Or
s = s.replaceAll(".*-(.*?)\\?.*", "$1");
Alternative regex:
"-a-(.+?)\\?"
Regex in testbench and context:
public static void main(String[] args) {
String input1 = "location/city/home-a-berlin?/someNewAdress";
List<String> inputs = Arrays.asList(input1);
Pattern pattern = Pattern.compile("-a-(.+?)\\?");
List<String> results = inputs.stream().map(s -> pattern.matcher(s))
.filter(Matcher::find).map(m -> m.group(1)).collect(Collectors.toList());
//Output:
results.forEach(System.out::println);
}
Output:
berlin
Summary of regular-expression constructs:
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html
Suppose I have a string like
"resources/json/04-Dec/someName_SomeTeam.json"
In above string I want just "04-Dec" part, this may change to "12-Jan" like this or any date with month with that format. How do I do this?
You can split using / and get the value 2
String text = "resources/json/04-Dec/someName_SomeTeam.json";
String[] split = text.split("\\/");
String result = split[2];//04-Dec
Or you can use patterns with this regex \d{2}\-\[A-Z\]\[a-z\]{2}:
String text = "resources/json/04-Dec/someName_SomeTeam.json";
String regex = "\\d{2}\\-[A-Z][a-z]{2}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println(matcher.group());
}
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"
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
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");
Hi I am trying to build one regex to extract 4 digit number from given string using java. I tried it in following ways:
String mydata = "get the 0025 data from string";
Pattern pattern = Pattern.compile("^[0-9]+$");
//Pattern pattern = Pattern.compile("^[0-90-90-90-9]+$");
//Pattern pattern = Pattern.compile("^[\\d]+$");
//Pattern pattern = Pattern.compile("^[\\d\\d\\d\\d]+$");
Matcher matcher = pattern.matcher(mydata);
String val = "";
if (matcher.find()) {
System.out.println(matcher.group(1));
val = matcher.group(1);
}
But it's not working properly. How to do this. Need some help. Thank you.
Change you pattern to:
Pattern pattern = Pattern.compile("(\\d{4})");
\d is for a digit and the number in {} is the number of digits you want to have.
If you want to end up with 0025,
String mydata = "get the 0025 data from string";
mydata = mydata.replaceAll("\\D", ""); // Replace all non-digits
Pattern pattern = Pattern.compile("\\b[0-9]+\\b");
This should do it for you.^$ will compare with the whole string.It will match string with only numbers.
Remove the anchors.. put paranthesis if you want them in group 1:
Pattern pattern = Pattern.compile("([0-9]+)"); //"[0-9]{4}" for 4 digit number
And extract out matcher.group(1)
Many better answers, but if you still have to use in the same way.
String mydata = "get the 0025 data from string";
Pattern pattern = Pattern.compile("(?<![-.])\\b[0-9]+\\b(?!\\.[0-9])");
Matcher matcher = pattern.matcher(mydata);
String val = "";
if (matcher.find()) {
System.out.println(matcher.group(0));
val = matcher.group(0);
}
changed matcher.group(1); to matcher.group(0);
You can go with \d{4} or [0-9]{4} but note that by specifying the ^ at the beginning of regex and $ at the end you're limiting yourself to strings that contain only 4 digits.
My recomendation: Learn some regex basics.
Scanner sc=new Scanner(System.in);
HashMap<String,String> a=new HashMap<>();
ArrayList<String> b=new ArrayList<>();
String s=sc.nextLine();
Pattern p=Pattern.compile("\\d{4}");
Matcher m=p.matcher(s);
while(m.find())
{
String x="";
x=x+(m.group(0));
a.put(x,"0");
b.add(x);
}
System.out.println(a.size());
System.out.println(b);
You can find all matched digit patterns and unique patterns (for unique use Set<String> k=b.keySet();)
If you want to match any number of digits then use pattern like the following:
^\D*(\d+)\D*$
And for exactly 4 digits go for
^\D*(\d{4})\D*$
How could I get the first and the second text in "" from the string?
I could do it with indexOf but this is really boring ((
For example I have a String for parse like: "aaa":"bbbbb"perhapsSomeOtherText
And I d like to get aaa and bbbbb with the help of Regex pattern - this will help me to use it in switch statement and will greatly simplify my app/
If all that you have is colon delimited string just split it:
String str = ...; // colon delimited
String[] parts = str.split(":");
Note, that split() receives regex and compilies it every time. To improve performance of your code you can use Pattern as following:
private static Pattern pColonSplitter = Pattern.compile(":");
// now somewhere in your code:
String[] parts = pColonSplitter.split(str);
If however you want to use pattern for matching and extraction of string fragments in more complicated cases, do it like following:
Pattert p = Patter.compile("(\\w+):(\\w+):");
Matcher m = p.matcher(str);
if (m.find()) {
String a = m.group(1);
String b = m.group(2);
}
Pay attention on brackets that define captured group.
Something like this?
Pattern pattern = Pattern.compile("\"([^\"]*)\"");
Matcher matcher = pattern.matcher("\"aaa\":\"bbbbb\"perhapsSomeOtherText");
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
aaa
bbbbb
String str = "\"aaa\":\"bbbbb\"perhapsSomeOtherText";
Pattern p = Pattern.compile("\"\\w+\""); // word between ""
Matcher m = p.matcher(str);
while(m.find()){
System.out.println(m.group().replace("\"", ""));
}
output:
aaa
bbbbb
there are several ways to do this
Use StringTokenizer or Scanner with UseDelimiter method