I need replace {word} by a regex named group: (?< word >\w++) to future match expressions, i.e.: /{name}/{age}... This code doesn't work!
String p = "/{name}/{id}";
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\\\w+)");
Pattern URL_PATTERN = Pattern.compile(p);
CharSequence cs = "/lucas/3";
Matcher m = URL_PATTERN.matcher(cs);
if(m.matches()){
for(int i=1;i<m.groupCount();++i){
System.out.println(m.group("name"));
}
}
Result: nothing :(
But when I get the result of replacement: /(?\w+)/(?\w+) and put in Pattern.compile() this works:
String p = "/{name}/{id}";
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\\\w+)");
Pattern URL_PATTERN = Pattern.compile("/(?<name>\\w+)/(?<id>\\w+)");
System.out.println(p);
CharSequence cs = "/lucas/3";
Matcher m = URL_PATTERN.matcher(cs);
if(m.matches()){
for(int i=1;i<m.groupCount();++i){
System.out.println(m.group("name"));
}
}
Result: "lucas"
What's wrong?
I think you used too many \ in your replace. Try
p = p.replaceAll("\\{(\\w+)\\}", "(?<$1>\\\\\\w+)");
Related
Here is my code:
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern
Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch
String store= "";
// print match and store match in String Store
if (m.find())
{
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
//repeat the process
Pattern p1 = Pattern.compile("(.*)[^\\/]");
Matcher m1 = p1.matcher(store);
if (m1.find())
{
String theGroup = m1.group(0);
System.out.format("'%s'\n", theGroup);
}
I want to to match everything that is after excludethis and before a / that comes after.
With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.
Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.
Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,
(?<=.com/excludethis).*(?=/)
Also, in Java you don't need to escape /
Your modified code,
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch
String store = "";
// print match and store match in String Store
if (m.find()) {
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
System.out.println("Store: " + store);
Prints,
'123456'
Store: 123456
Like you wanted to capture the value.
This may be useful for you :)
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
If you don't want to use regex, you could just try with String::substring*
String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));
Output:
123456
* Definitely don't actually use this
how to get all word if it has _I, im using "\S_I+\S".
I Have String :
the_B-NP camera_I-NP is_B-VP very_B-ADJP easy_I-ADJP to_B-VP use_I-VP ,_O in_B-PP fact_B-NP on_B-PP a_B-NP recent_I-NP trip_I-NP this_B-NP past_I-NP week_I-NP i_I-NP was_B-VP asked_I-VP to_B-VP take_I-VP a_B-NP picture_I-NP of_B-PP a_B-NP vacationing_I-NP elderly_I-NP group_I-NP ._O
this my code
Pattern p = Pattern.compile("\\S*_I+\\S*");
Matcher m = p.matcher(input);
while(m.find()){
hasilReg = m.group();
}
after compile i got only one value : group_I-NP
but i would like all word if it has _I
thanks
The group_I-NP is the last value and you only get this because you reassign the hasilReg value all the time. Add the results to a List<String>:
String str = "the_B-NP camera_I-NP is_B-VP very_B-ADJP easy_I-ADJP to_B-VP use_I-VP ,_O in_B-PP fact_B-NP on_B-PP a_B-NP recent_I-NP trip_I-NP this_B-NP past_I-NP week_I-NP i_I-NP was_B-VP asked_I-VP to_B-VP take_I-VP a_B-NP picture_I-NP of_B-PP a_B-NP vacationing_I-NP elderly_I-NP group_I-NP ._O ";
Pattern ptrn = Pattern.compile("\\S*_I+\\S*");
Matcher matcher = ptrn.matcher(str);
List<String> lst = new ArrayList<>();
while (matcher.find()) {
lst.add(matcher.group());
}
System.out.println(lst);
// => [camera_I-NP, easy_I-ADJP, use_I-VP, recent_I-NP, trip_I-NP, past_I-NP, week_I-NP, i_I-NP, asked_I-VP, take_I-VP, picture_I-NP, vacationing_I-NP, elderly_I-NP, group_I-NP]
See the Java demo
I'm trying to get the last return code from an SSH shell in linux.
I'm using the command:echo &? to get it.
I've written following code but it's not working:
int last_len = 0;
Pattern p = Pattern.compile("echo $?\r\n[0-9]");
while(in.available() > 0 ) {
last_len = in.read(buffer);
String str = new String(buffer, 0, last_len);
Matcher m = p.matcher(str);
if(m.find()) {
return Integer.parseInt(m.group().substring(9));
}
}
What am I doing wrong?
You need to escape $, ? in the regex inorder to match the literal form of those characters since ?, $ are considered as special chars in regex.
Pattern p = Pattern.compile("echo \\$\\?\\r?\\n([0-9])");
Matcher m = p.matcher(str);
if(m.find()) {
System.out.println(m.group(1));
}
or
Pattern p = Pattern.compile("echo\\s+\\$\\?[\\r\\n]+([0-9])");
I have string like
{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}
{Imapact}{assest}{custom_23_multiplication}.
From this I want only those sub string which contains "custom".
For example from above string I want only
{Custom_21_addtion}{custom_22_substration}{custom_23_multiplication}.
How can I get this?
You can use a regular expression, looking from {custom to }. It will look like this:
Pattern pattern = Pattern.compile("\\{custom.*?\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
System.out.print(matcher.group());
}
The .* after custom means 0 or more characters after the word "custom", and the question mark limits the regex to as few character as possible, meaning that it will break on the next } that it can find.
If you want an alternative solution without regex:
String a = "{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}{custom_23_multiplication}";
String[] b = a.split("}");
StringBuilder result = new StringBuilder();
for(String c : b) {
// if you want case sensitivity, drop the toLowerCase()
if(c.toLowerCase().contains("custom"))
result.append(c).append("}");
}
System.out.println(result.toString());
you can do it sth like this:
StringTokenizer st = new StringTokenizer(yourString, "{");
List<String> llista = new ArrayList<String>():
Pattern pattern = Pattern.compile("(\W|^)custom(\W|$)", Pattern.CASE_INSENSITIVE);
while(st.hasMoreTokens()) {
String string = st.nextElement();
Matcher matcher = pattern.matcher(string);
if(matcher.find()){
llista.add(string);
}
}
Another solution:
String inputString = "{Action}{RequestId}{Custom}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}" ;
String strTokens[] = inputString.split("\\}");
for(String str: strTokens){
Pattern pattern = Pattern.compile( "custom", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
System.out.println("Tag Name:" + str.replace("{",""));
}
}
I have sentence and I want to calculate words, semiPunctuation and endPunctuation in it.
Command "m.group()" will show String result. But how to know which group is found?
I can use method with "group null", but it is sounds not good.
String input = "Some text! Some example text."
int wordCount=0;
int semiPunctuation=0;
int endPunctuation=0;
Pattern pattern = Pattern.compile( "([\\w]+) | ([,;:\\-\"\']) | ([!\\?\\.]+)" );
Matcher m = pattern.matcher(input);
while (m.find()) {
// need more correct method
if(m.group(1)!=null) wordCount++;
if(m.group(2)!=null) semiPunctuation++;
if(m.group(3)!=null) endPunctuation++;
}
You could use named groups to capture the expressions
Pattern pattern = Pattern.compile( "(?<words>\\w+)|(?<semi>[,;:\\-\"'])|(?<end>[!?.])" );
Matcher m = pattern.matcher(input);
while (m.find()) {
if (m.group("words") != null) {
wordCount++;
}
...
}