How can I find a digit after string with pattern? - java

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])");

Related

How to replace string pattern by one character of length of matching substring length?

My attempt:
StringBuffer bf = new StringBuffer();
Pattern emailPattern = Pattern.compile("(?<=.)(.*?)(?=#)");
Matcher m = emailPattern.matcher("abc123#gmail.com");
while(m.find()){
m.appendReplacement(bf, "*");
}
return bf.toString();
The problem is this code returns "a*#gmail.com", but I want it to return "a*****#gmail.com" where the number of "*" is the number of replaced characters.
Thanks.
With the pattern you could call this instead:
String obfuscate = emailPattern.matcher(email).replaceAll(
m -> "*".repeat(m.group().length()));
(String.repeat from Java 11, this Matcher.replaceAll from Java 9)
Using earlier versions of Java:
while(m.find()) {
char[] replace = new char[m.group().length()];
Arrays.fill(replace, '*');
m.appendReplacement(bf, new String(replace));
}
m.appendTail(bf);

Matcher. How to get index of found group?

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++;
}
...
}

Java regex - why did the Matcher find extra characters?

I was experimenting trying to extract the 't' and 'f' flags from here.
So I was surprised to see extra characters in the output. Apparently the matcher backtracked - I dont understand why. What should be the correct regex?
System.out.println("searching...");
// "Sun:\\s Mon:\\s Tue:\\s Wed:\\s Thu:\\s Fri:\\s Sat:\\s "
Pattern p = Pattern.compile("[t|f]");
Matcher m = p.matcher("Sun:t Mon:f Tue:t Wed:t Thu:f Fri:t Sat:f ");
while (m.find()) {
System.out.println(m.group());
}
Output:
searching...
t
f
t
t
f
t
t
f
Sat has a t in it. Try ":([tf])" instead.
Pattern p = Pattern.compile(":([tf])");
Matcher m = p.matcher("Sun:t Mon:f Tue:t Wed:t Thu:f Fri:t Sat:f ");
while (m.find()) {
System.out.println(m.group(1));
}

Java URL regex not matching

I am trying to count the number of URLs in a Java string:
String test = "This http://example.com is a sentence https://secure.whatever.org that contains 2 URLs.";
String urlRegex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]>";
int numUrls = 0;
pattern = Pattern.compile(urlRegex);
matcher = pattern.matcher(test);
while(matcher.find())
numUrls++;
System.err.println("numUrls = " + numUrls);
When I run this it tells me I have zero (not 2) URLs in the string. Any ideas as to why? Thanks in advance!
The < and > characters in urlRegex are causing a mismatch between your pattern and your input test String. Removing them will yield a numUrls value of 2 as intended.
Try this code :
String data = "This http://example.com is a sentence https://secure.whatever.org that contains 2 URLs.";
Pattern pattern = Pattern.compile("[hH][tT]{2}[Pp][sS]?://(\\w+(\\.\\w+?)?)+");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
System.out.println(matcher.group());
}
Hopefully it will work.

What's wrong with this replacement code?

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+)");

Categories