I am trying to search a for a specific string in an HTML file. The string I am looking for is
HHA_HG
If I use notepad I can see that the string only exists once in the file.
However
MatchCollection matches = Regex.Matches(inputString, "HHA_HG");
Returns no matches. I verify the inputString contains the string I want.
The weird thing is if I remove all the lines apart from the line containing HHA_HG I can get a match. If I just search for HHA_ in the full file I can get matches although none of the matches are HHA_HG.
Does the underscore mean something special?
No, it does not. That should be fine. Possible explanation: is there an invisible unicode character in either the source or regex pattern? Or alternative "looks like an A but isn't an A" unicode characters? Basically, what are the actual char values in both the regex pattern and the file (at the appropriate location)? Is the HHA_HG in the file actually in a RTL block, and is actually GH_AHH ?
Related
So i have the following RegEx for the purpose of finding and adding whitespace:
(\S)(\()
So for a string like "SomeText(Somemoretext)" I want to update this to "SomeText (Somemoretext)" it matches "t(" and so my replace eliminates the "t" from the string which is not good. I also do not know what the character could be, I'm merely trying to find the non-existence of whitespace.
Is there a better expression to use or is there a way to exclude the found character from the match returned so that I can safely replace without catching characters i do not want to replace?
Thanks
I find lookarounds hard to read and would prefer using substitutions in the replacement string instead:
var s = Regex.Replace("test1() test2()", #"(\S)\(", "$1 (");
Debug.Assert(s == "test1 () test2 ()");
$1 inserts the first capture group from the regex into the replacement string which is the non-space character before the opening parenthesis (.
If you need to detect the absence of space before a specific character (such as bracket) after a word, how about the following?
\b(?=[^\s])\(
This will detect words ( [a-zA-z0-9_] that are followed by a bracket, without a space).
(if I got your problem correctly) you can replace the full match with ( and get exactly what you need.
In case you need to look for absence spaces before a symbol (like a bracket) in any kind of text (as in the text may be non-word, such as punctuation) you might want to use the following instead.
^(?:\S*)(\()(?:\S*)$
When using this, your result will be in group 1, instead of just full match (which now contains the whole line, if a line is matched).
I'v searched extensively but I can't find a simple answer to this and my Regex experience is limited. I'd appreciate a simple solution that is explained, please.
I have a very large string and I need to substitute certain words in it as follows:
Example: wherever you find the string "LINK-ABC" make it "LINK_ABC".
I wrote my Regex Match and Replace strings:
#"LINK-ABC", #"LINK_ABC" and it worked.
But there were a couple of things I had not recognized.
There COULD be words in the file like this:
LINK-ABC-DEF LINK-ABC-GHI-JKL ... and so on.
So I get "LINK_ABC-DEF" etc. (which is NOT what I want; this should have remained intact...)
Once I realized the problem it seemed that what I REALLY wanted was to recognize ONLY the word being matched and leave any cases where it was in combination with something else, unchanged. It seemed to me that if I checked for a space or period on the Match word, that should do it, so...
#"LINK-ABC[ |\\.]",#"LINK_ABC"
... and now I have stumbled.
Sample string:
link-xxx link-aaa-sss link-xxx-bbb link-xxx link-xxx.
Match/Replace string:
link-xxx[ |\\.],link_xxx
Result string:
link_xxxlink-aaa-sss link-xxx-bbb link_xxxlink_xxx
The replacements are correct, BUT the trailing comma or period has been "devoured" and so the result string is wrong.
Is there a way that I can match so that if it matches on space, the replacement will have a space and if it matches on a period, the replacement will have a period? I s'pose I could do 2 separate matches but I'd like to increase my understanding of Regex and do it more elegantly if it is possible.
You should be able to achieve the behavior you want with "capture groups"
var matchstring = #"link-xxx([ \.]|$)";
var fixstr = #"link_xxx$1";
The parenthesis around the last part of the matchstring will retain whatever matched inside it, and the $1 in the fixstr will substitute whatever was captured by that group.
I've also modified your punctuation section a little bit, presuming you want to replace a match if it happens to be the last word in the input (by adding the |$). A | inside a character class [] is a literal | character, so I removed it assuming you don't actually expect that in your input.
If I need to allow only first punctuation mark in string with different punctuation marks sequence between words, for example if string is:
string str = "hello,.,.,.world.,.?,.";
in result I want get this:
hello, world.
It would be good to know both, how to pass such string after insert and how to avoid writing of more then one mark and one white space between the words in string directly in textbox.
You can try this: (?<=[,.])[,.?]+.
See it working here: https://regex101.com/r/di5Ebw/1.
If you need to have a list of special ponctuation that you want to strip we can adjust in [,.]!
(So in the example I give you the match is on the chars you want to remove: just replace that match with empty string - as you can see in the SUBSTITUTION panel at the bottom)
[EDIT] Extend the match cases.
If you don't want to bother let this do it for you: (?<=\W)(?<! )\W+
See it working here: https://regex101.com/r/di5Ebw/2
.Net regular expressions have a punctuation class, so a simple way of achieving the required result is to search for the string (\w\p{P})\p{P}+ and replace with $1.
For a regular expression that handles exactly the few punctuation characters used in the question the regular expression (\w[.,?])[.,?]+ can be used.
(Note, the above shows the regular expressions. Their C# strings are "(\\w\\p{P})\\p{P}+" and "(\\w[.,?])[.,?]+".)
Explanation. This looks for a word character (\w) followed by one punctuation character and it captures these two characters. Any immediately following punctuation characters are matched by the \p{P}+. The whole match is replace by the capture.
The \p{name} construct is defined here as "Matches any single character in the Unicode general category or named block specified by name.
".
The \p{P} category is defined here as "All punctuation characters". There are also several subcategories of punctuation, but it may be best to look at Unicode to understand them.
I have a Regex that I now need to moved into C#. I'm getting errors like this
Unrecognized escape sequence
I am using Regex.Escape -- but obviously incorrectly.
string pattern = Regex.Escape("^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!##$%\?\(\)\*\&\^\-\+\=_])).*$");
hiddenRegex.Attributes.Add("value", pattern);
How is this correctly done?
The error you're getting is coming at compile time correct? That means C# compiler is not able to make sense of your string. Prepend # sign before the string and you should be fine. You don't need Regex.Escape.
See What's the # in front of a string in C#?
var pattern = new Regex(#"^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!##$%\?\(\)\*\&\^\-\+\=_])).*$");
pattern.IsMatch("Your input string to test the pattern against");
The error you are getting is due to the fact that your string contains invalid escape sequences (e.g. \d). To fix this, either escape the backslashes manually or write a verbatim string literal instead:
string pattern = #"^.*(?=.{7,})(?=.*[a-zA-Z])(?=.*(\d|[!##$%\?\(\)\*\&\^\-\+\=_])).*$";
Regex.Escape would be used when you want to embed dynamic content to a regular expression, not when you want to construct a fixed regex. For example, you would use it here:
string name = "this comes from user input";
string pattern = string.Format("^{0}$", Regex.Escape(name));
You do this because name could very well include characters that have special meaning in a regex, such as dots or parentheses. When name is hardcoded (as in your example) you can escape those characters manually.
hi , I have 2 related questions.
1)suppose we have:
string strMessage="\nHellow\n\nWorld";
console.writeln(strMessage);
Result is:
Hellow
World
Now if we want to show the string in the original format in One Line
we must redefine the first variable from scratch.
string strOrignelMessage=#"\nHellow\n\nWorld" ;
console.writln(strOrignelMessage);
Result is:
\nHellow\n\nWorld --------------------->and everything is ok.
i am wondering is there a way to avoid definning
the new variable(strOrignelMessage) in code for this purpose and just using only
the first string variable(strMessage) and apply some tricks and print it in one line.
at first i tried the following workaround but it makes some bugs.suppose we have:
string strMessage="a\aa\nbb\nc\rccc";
string strOrigenalMessage=strMessage.replace("\n","\\n").replace("\r","\\r");
Console.writeln(strOrigenalMessage)
result is :aa\nbb\nc\rccc
notice that befor the first "\" not printed.and now my second question is:
2)How we can fix the new problem with single "\"in the string
i hope to entitle this issue correctly and my explanations would be enough,thanks
No, because the compiler has already converted all of your escaped characters in the original string to the characters they represent. After the fact, it is too late to convert them to non-special characters. You can do a search and replace, converting '\n' to literally #"\n", but that is whacky and you're better off defining the string correctly in the first place. If you wanted to escape the backslashes in the first place, why not put an extra backslash character in front of each of them:
Instead of "\n" use "\\n".
Updated in response to your comment:
If the string is coming from user input, you don't need to escape the backslash, because it will be stored as a backslash in the input string. The escape character only works as an escape character in string literals in code (and not preceded by #, which makes them verbatim string literals).
if you want "\n\n\a\a\r\blah" to print as \n\n\a\a\r\blah without # just replace all \ with \\
\ is the escaper in a non-verbatim string. So you simply need to escape the escaper, as it were.
If you want to use both strings, but want to have only one in the code then write the string with #, and construct the other one with Replace(#"\n","\n").
explanations for Anthony Pegram (if i understand u right) and anyone that found it usefull
i think i find my way in question2.
at first ,unfortunately,i thought that the
escape characters limts to \n,\t,\r,\v and
this made me confuesed becouse in my sample string i used \a and \b
and the compiler behaviuor was not understandable for me.
but finally i found that \a and \b is in
escape-characters set too.and if u use "\" without escap characters
a compile time error would be raised (its so funny when i think to My mistake again)
pls refers to this usefull msdn article for more info.
2.4.4.5 String literals
and you couldnt replace \ (single\) with \\
becouse fundamentally you couldnt have a (single \) without using
escape-characters after it in a string .so we coudnt write such a string in the code:
string strTest="abc\pwww"; ------> compile time error
and for retriving an inactived escape characters version of a string
we can use simply string.replace method as i used befor.
excuse me for long strory ,thank u all for cooperation.