String Replacing in Regex - regex

I am trying to replace text in string using regex. I accomplished it in c# using the same pattern but in swift its not working as per needed.
Here is my code:
var pattern = "\\d(\\()*[x]"
let oldString = "2x + 3 + x2 +2(x)"
let newString = oldString.stringByReplacingOccurrencesOfString(pattern, withString:"*" as String, options:NSStringCompareOptions.RegularExpressionSearch, range:nil)
print(newString)
What I want after replacement is :
"2*x + 3 +x2 + 2*(x)"
What I am getting is :
"* + 3 + x2 +*)"

Try this:
(?<=\d)(?=x)|(?<=\d)(?=\()
This pattern matches not any characters in the given string, but zero width positions in between characters.
For example, (?<=\d)(?=x) This matches a position in between a digit and 'x'
(?<= is look behind assertion (?= is look ahead.
(?<=\d)(?=\() This matches the position between a digit and '('
So the pattern before escaping:
(?<=\d)(?=x)|(?<=\d)(?=\()
Pattern, after escaping the parentheses and '\'
\(?<=\\d\)\(?=x\)|\(?<=\\d\)\(?=\\\(\)

Related

Regex for set of 6 digits from 1-49

I've a problem with define regular expression correctly. I want check sets of digits f.e.: 1,2,14,15,16,17 or 12,13,14,15,16,17 or 1,2,3,6,7,8. Every set contains 6 digits from 1 to 49. I check it by input's pattern field.
I wrote some regex but it works only for 2-digit sets.
([1-9]|[1-4][0-9],){5}([1-9]|[1-4][0-9])
Thanks for all answers :)
You forgot to group the number patterns inside the quantified group before comma and the anchors to make the regex engine match the full input string:
^(?:(?:[1-9]|[1-4][0-9]),){5}(?:[1-9]|[1-4][0-9])$
^ ^^^ ^ ^
See the regex demo.
Details
^ - start of string
(?:(?:[1-9]|[1-4][0-9]),){5} - five occurrences of:
(?:[1-9]|[1-4][0-9]) - either a digit from 1 to 9 or a number from 10 to 49`
, - a comma
(?:[1-9]|[1-4][0-9])
$ - end of string.
JS demo:
var strs = ['1,2,14,15,16,17','12,13,14,15,16,17', '1,2,3,6,7,8', '1,2,3,6,7,8,'];
var rng = '(?:[1-9]|[1-4][0-9])';
var rx = new RegExp("^(?:" + rng + ",){5}" + rng + "$");
for (var s of strs) {
console.log(s, '=>', rx.test(s));
}

.Net Regular Expression(Regex)

VB.NET separate strings using regex split?
Im having a logical error with the pattern string variable, the error occur after i extend the string from "(-)" to "(-)(+)(/)(*)"..
Dim input As String = txtInput.Text
Dim pattern As String = "(-)(+)(/)(*)"
Dim substrings() As String = Regex.Split(input, pattern)
For Each match As String In substrings
lstOutput.Items.Add(match)
This is my output when my pattern string variable is "-" it works fine
input: dog-
output: dog
-
My desired output(This is want i want to happen) but there is something wrong with the code.. its having an error after i did this "(-)(+)(/)()" even this
"(-)" + "(+)" + "(/)" + "()"
input: dog+cat/tree
output: dog
+
cat
/
tree
when space character input from textbox to listbox
input: dog+cat/ tree
output: dog
+
cat
/
tree
You need a character class, not the sequence of subpatterns inside separate capturing gorups:
Dim pattern As String = "([+/*-])"
This pattern will match and capture into Group 1 (and thus, all the captured values will be part of the resulting array) a char that is either a +, /, * or -. Note the position of the hyphen: since it is the last char in the character class, it is treated as a literal -, not a range operator.
See the regex demo:

Remove optional whitespace when splitting with math operators while keeping them in the result

How to remove whitespace characters from the input string? I am using the following code that
Dim input As String = txtInput.Text
Dim symbol As String = "([-+*/])"
Dim substrings() As String = Regex.Split(input, symbol)
Dim cleaned As String = Regex.Replace(input, "\s", " ")
For Each match As String In substrings
lstOutput.Items.Add(match)
Next
Input: z + x
Output: z, + and x.
I want to get rid of the whitespace in the last item.
You may remove the redundant whitespace while splitting with
\s*([-+*/])\s*
See the regex demo. Also, it is a good idea to trim the input before passing to the regex replace method with .Trim().
Pattern details:
\s* - matches 0+ whitespaces (these will be discarded from the result as they are not captured)
([-+*/]) - Group 1 (captured texts will be output to the resulting array) capturing 1 char: -, +, * or /
\s* - matches 0+ whitespaces (these will be discarded from the result as they are not captured)

Regex: match and tokenize in Scala

I am trying to extract certain patterns from the input string. These patterns are +, - , *, / , (, ), log , integer and float numbers.
Here's example for the needed behavior:
//input string
var str = "log6*(12+5)/2-34.2"
//wanted result
var rightResp = Array("log","6","*","(","12","+","5",")","/","2","-","34.2")
I have tried to do this for some time but I have to admit that regex is not my specialty. Next piece of code shows where I am stuck:
import scala.util.matching.Regex
var str = "log6*(12+5)/2-34.2"
val pattern = new Regex("(\\+|-|log|\\*|\\/|[0-9]*\.?[0-9]*)")
pattern.findAllIn(str).toArray
Result is not good cause there is no matching for brackets "(" and ")" and also numbers , both integer(6,12,5,2) and float(34.2) are messed up. Thanks for your help!
You can use
[+()*/-]|log|[0-9]*\\.?[0-9]+
See regex demo
The regex contains 3 alternatives joined with the help of | alternation operator.
[+()*/-] - matches a single literal character: +, (, ), *, /, - (note that the hyphen is not escaped as it is at the end of the character class)
log - a literal letter sequence log
[0-9]*\\.?[0-9]+ - a float number that accepts values like .05, 5.55 as it matches...
[0-9]* - 0 or more digits
\\.? - and optional (1 or 0) literal periods
[0-9]+ - 1 or more digitis.
Here is a Scala code sample:
import scala.util.matching.Regex
object Main extends App {
var str = "log6*(12+5)/2-34.2"
val pattern = new Regex("[+()*/-]|log|[0-9]*\\.?[0-9]+")
val res = pattern.findAllIn(str).toArray
println(res.deep.mkString(", "))
}
Result: log, 6, *, (, 12, +, 5, ), /, 2, -, 34.2

Wrong return from Regex.IsMatch - Regular expression

I want to find in string a specific string surrounded by white spaces. For example I want receive the value true from:
Regex.IsMatch("I like ZaleK", "zalek",RegexOptions.IgnoreCase)
and value false from:
Regex.IsMatch("I likeZaleK", "zalek",RegexOptions.IgnoreCase)
Here is my code:
Regex.IsMatch(w_all_file, #"\b" + TB_string.Text.Trim() + #"\b", RegexOptions.IgnoreCase) ;
It does not work when in the w_all_file is string I am looking for followed by "-"
For example: if w_all_file = "I like zalek_" - the string "zalek" is not found, but if
w_all_file = "I like zalek-" - the string "zalek" is found
Any ideas why?
Thanks,
Zalek
The \b character in regex doesn't consider an underscore as word boundry. You might want to change it to something like this:
Regex.IsMatch(w_all_file, #"[\b_]" + TB_string.Text.Trim() + #"[\b_]", RegexOptions.IgnoreCase) ;
That's what you need?
string input = "type your name";
string pattern = "your";
Regex.IsMatch(input, " " + pattern + " ");
\b matches at a word boundary, which are defined as between a character that is included in \w and one that is not. \w is the same as [a-zA-Z0-9_], so it matches underscores.
So basically, \b will match after the "k" in zalek- but not in zalek_.
It sounds like you want the match to also fail on zalek-, which you can do by using lookaround. Just replace the \b at the beginning with (?<![\w-]), and replace the \b at the end with (?![\w-]):
Regex.IsMatch(w_all_file, #"(?<![\w-])" + TB_string.Text.Trim() + #"(?![\w-])", RegexOptions.IgnoreCase) ;
Note that if you add additional characters to the character class [\w-], you need to make sure that the "-" is the very last character, or that you escape it with a backslash (if you don't it will be interpreted as a range of characters).