I am using regex in this line of code:
if (line.matches("^.*\b(" + incomingMachineIP + ")\b.*$"))
So, assume the following inputs:
incomingMachineIp = "10.10.10.10"
line = "abcde=10.10.10.10abcedf"
I want the if condition to return true, which is what I'm trying to do with the regex above however a false is still returned even though the value of incomingMachineIp is found in the string (line)
Any help how to resolve this would be greatly appreciated.
In your example you can simply use line.contains(incomingMachineIP) and don't have to deal with regex patterns at all.
You need to escape the backslash one more times and also you need to remove the second \b or replace with \B because there isn't a word boundary exists between the last 0 and the letter a
if(line.matches(".*\\b" + Pattern.quote(incomingMachineIP) + ".*"))
Since you're using matches method, it won't require anchors.
use a live Regex Console to test your expressions until you have got it working. Just remember to replace any single character backslash "\" with a double backslash character "\\" before using your expression in java!
Related
I want to remove multiple occurrences of special characters like " ", "-", "!", "_" from my java string by a single underscore "_".
I tried
replaceAll("([\\s\\-\\!])\\1+","_")
and it seems to replace consecutive same type of special character by a underscore but doesn't work otherwise.
for eg:
Hello!!! World
becomes
Hello__World
(2 underscores.)But It should be Hello_World.
Also for cases like Hello - World it fails.
I also tried working with regex and made a regular expression like
replaceAll("([^a-zA-Z0-9])\\1+","_")
but it still doesn't help. How can I achieve it?
Note that \1 is a backreference to the contents matched with the first capturing group. To actually match one or more any characters from the character class, just use a + quantifier:
[\\s!-]+
So, use
str = str.replaceAll("[\\s!-]+","_");
See IDEONE demo
(Hoping to write a good question).
I have to match a RPG function in Java, using regular expressions.
The functions I have are in these possible ways:
nameFunction()
nameFunction(params)
nameFunction('otherFunction(' + variable + ')')
nameFunction('otherFunction.get('''+trim(string_variable)+''')')
fun1() + fun2()
Where the ' is used to open/close string, and ' is used also as escape char for ' itself.
I've already tried with this regex:
\w+\([^\)]*\)
Where with \w+ I want to match the name, then the (, all chars but no the close parenthesis and finally the closed one.
The first two functions are correctly recognized, but the third and fourth ones no. Regex matchs
nameFunction('otherFunction(' + variable + ')
nameFunction('otherFunction.get('''+trim(string_variable)
skipping the last closed parenthesis in the third and the string concatenation in the fourth (the fifth example is to show that I can have multiple functions and I want to recognize them separately).
Any suggestions? Thanks in advance.
If the strings have no escapes you could use:
\w+\((?:[^'()]|'[^']*')*\)
If you want to handle backslash escapes you could do that with:
\w+\((?:[^'()]|'(?:[^'\\]|\\.)*')*\)
Your problem is that you don't allow the closing bracket in the functions params.
\w+\(.*\)
this would do the trick.
If you just want to match text before first ( and all the text between outermost parenthesis then this negative lookahead based regex will work for you:
Pattern p = Pattern.compile("(\\w+)\\s*\\((.*?)\\)(?![^)]*\\))");
Worked with all 4 of your examples.
Online Demo: http://fiddle.re/rmy3a
I'm trying to write a regular expression that checks ahead to make sure there is either a white space character OR an opening parentheses after the words I'm searching for.
Also, I want it to look back and make sure it is preceded by either a non-Word (\W) or nothing at all (i.e. it is the beginning of the statement).
So far I have,
"(\\W?)(" + words.toString() + ")(\\s | \\()"
However, this also matches the stuff at either ends - I want this pattern to match ONLY the word itself - not the stuff around it.
I'm using Java flavor Regex.
As you tagged your question yourself, you need lookarounds:
String regex = "(?<=\\W|^)(" + Pattern.quote(words.toString()) + ")(?= |[(])"
(?<=X) means "preceded by X"
(?<!=X) means "not preceded by X"
(?=X) means "followed by X"
(?!=X) means "not followed by X"
What about the word itself: will it always start with a word character (i.e., one that matches \w)? If so, you can use a word boundary for the leading condition.
"\\b" + theWord + "(?=[\\s(])"
Otherwise, you can use a negative lookbehind:
"(?<!\\w)" + theWord + "(?=[\\s(])"
I'm assuming the word is either quoted like so:
String theWord = Pattern.quote(words.toString());
...or doesn't need to be.
If you don't want a group to be captured by the matching, you can use the special construct (?:X)
So, in your case:
"(?:\\W?)(" + words.toString() + ")(?:\\s | \\()"
You will only have two groups then, group(0) for the whole string and group(1) for the word you are looking for.
I am having some problem with searching for a special character "(".
I got a java.util.regex.PatternSyntaxException exception has occurred.
It might have something to do with "(" being treated as special character.
I am not very good with pattern expression. Can someone help me properly search for the escape character?
// I need to split the string at the "("
String myString = "Room Temperature (C)";
String splitList[] = myString.split ("("); // i got an exception
// I tried this but got compile error
String splitList[] = myString.split ("\(");
Try one of these:
string.split("\\(");
string.split(Pattern.quote("("));
Since a string split takes a regular expression as an argument, you need to escape characters properly. See Jon Skeet's answer on this here:
The reason you got an exception the first time is because split() takes a regular expression as argument, and ( has a special meaning there, as you suggest. To avoid this, you need to escape it using a \, like you tried.
What you missed, is that you also need to escape your backslashes with an extra \ in Java, meaning you need a total of two:
String splitList[] = myString.split ("\\(");
You need to escape the character via backslashes: string.split("\\(");
( is one of regex special characters. To escape it you can use e.g.
split(Pattern.quote("(")),
split("\\Q(\\E"),
split("\\("),
split("[(]").
I'm no expert in regex but I need to parse some input I have no control over, and make sure I filter away any strings that don't have A-z and/or 0-9.
When I run this,
Pattern p = Pattern.compile("^[a-zA-Z0-9]*$"); //fixed typo
if(!p.matcher(gottenData).matches())
System.out.println(someData); //someData contains gottenData
certain spaces + an unknown symbol somehow slip through the filter (gottenData is the red rectangle):
In case you're wondering, it DOES also display Text, it's not all like that.
For now, I don't mind the [?] as long as it also contains some string along with it.
Please help.
[EDIT] as far as I can tell from the (very large) input, the [?]'s are either white spaces either nothing at all; maybe there's some sort of encoding issue, also perhaps something to do with #text nodes (input is xml)
The * quantifier matches "zero or more", which means it will match a string that does not contain any of the characters in your class. Try the + quantifier, which means "One or more": ^[a-zA-Z0-9]+$ will match strings made up of alphanumeric characters only. ^.*[a-zA-Z0-9]+.*$ will match any string containing one or more alphanumeric characters, although the leading .* will make it much slower. If you use Matcher.lookingAt() instead of Matcher.matches, it will not require a full string match and you can use the regex [a-zA-Z0-9]+.
You have an error in your regex: instead of [a-zA-z0-9]* it should be [a-zA-Z0-9]*.
You don't need ^ and $ around the regex.
Matcher.matches() always matches the complete string.
String gottenData = "a ";
Pattern p = Pattern.compile("[a-zA-z0-9]*");
if (!p.matcher(gottenData).matches())
System.out.println("doesn't match.");
this prints "doesn't match."
The correct answer is a combination of the above answers. First I imagine your intended character match is [a-zA-Z0-9]. Note that A-z isn't as bad as you might think it include all characters in the ASCII range between A and z, which is the letters plus a few extra (specifically [,\,],^,_,`).
A second potential problem as Martin mentioned is you may need to put in the start and end qualifiers, if you want the string to only consists of letters and numbers.
Finally you use the * operator which means 0 or more, therefore you can match 0 characters and matches will return true, so effectively your pattern will match any input. What you need is the + quantifier. So I will submit the pattern you are most likely looking for is:
^[a-zA-Z0-9]+$
You have to change the regexp to "^[a-zA-Z0-9]*$" to ensure that you are matching the entire string
Looks like it should be "a-zA-Z0-9", not "a-zA-z0-9", try correcting that...
Did anyone consider adding space to the regex [a-zA-Z0-9 ]*. this should match any normal text with chars, number and spaces. If you want quotes and other special chars add them to the regex too.
You can quickly test your regex at http://www.regexplanet.com/simple/
You can check input value is contained string and numbers? by using regex ^[a-zA-Z0-9]*$
if your value just contained numberString than its show match i.e, riz99, riz99z
else it will show not match i.e, 99z., riz99.z, riz99.9
Example code:
if(e.target.value.match('^[a-zA-Z0-9]*$')){
console.log('match')
}
else{
console.log('not match')
}
}
online working example