Find Function with RichTextBox with Labels - richtextbox

What I'm trying to do is to make it where the user can type in a textbox and then click on a button and it will search the richtextbox for what they are looking for and if it found something it will change the label.
(Instances)
`
Button = btn_Search
Textbox = InputBox
RichTextBox = rtb
Label = Results`

Use this method, to find any Text inside your RichTextBox.
public int FindMyText(string searchText, int searchStart, int searchEnd)
{
// Initialize the return value to false by default.
int returnValue = -1;
// Ensure that a search string and a valid starting point are specified.
if (searchText.Length > 0 && searchStart >= 0)
{
// Ensure that a valid ending value is provided.
if (searchEnd > searchStart || searchEnd == -1)
{
// Obtain the location of the search string in richTextBox1.
int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
// Determine whether the text was found in richTextBox1.
if(indexToText >= 0)
{
// Return the index to the specified search text.
returnValue = indexToText;
}
}
}
return returnValue;
}
call this method like this:
var res= FindMyText("hello",0. richTextBox1.Text.Length);
now if res>-1, that means positive match, then you can set your labels i.e.
if(res>-1){
lbl1.Text = "hello found";
}
source here and here

Another method of searching text that is far more clean is as below,but first you need to add
System.Text.RegularExpressions namespace to your project;
private void SearchButton_Click(object sender, EventArgs e)
{
if (textBox1.TextLength >= 1)
{
string word = textBox1.Text;//The text you want to search.
Regex searchterm = new Regex(word);//A Regular Expression is most efficient way of working with text.
MatchCollection matches = searchterm.Matches(richTextBox1.Text);
if (matches.Count >= 1)
{
Results=matches.Count.ToString();//Your label to display match instances.
richTextBox1.SelectAll();
richTextBox1.SelectionBackColor = Color.White;
richTextBox1.DeselectAll();
foreach (Match match in matches)
{
richTextBox1.Select(match.Index, match.Length);
richTextBox1.SelectionBackColor = Color.Orange;
richTextBox1.DeselectAll();
}
}
}
}
This should do the job,furthermore if you want to specify additional search options,replace the line with Regex searchterm with anyone below,
Case Insensitive
Regex searchterm = new Regex(word,RegexOptions.IgnoreCase);
Whole Word Search
Regex searchterm = new Regex(#"\b"+word+"\b");
Case Insensitive and Whole Word Search
Regex searchterm = new Regex(#"\b"+word+"\b",RegexOptions.IgnoreCase);
and one more thing,Regex searches are case-sensitive by default.

Related

The operator '[]=' isn't defined for the type 'String'

I'm getting an error in this code:
void main() {
List<String> wave(String str) {
List<String> results = [];
String newStr;
int i = 0;
for (String ltr in str.split('')) {
newStr = str;
if (ltr != ' ') {
newStr[i] = ltr.toUpperCase();
results.add(newStr);
}
i++;
}
return results;
}
print(wave(' gap '));
}
the error is at the line:
newStr[i] = ltr.toUpperCase;
Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!
In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.
To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:
if (ltr != ' ' && i < newStr.length) {
newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
results.add(newStr);
}
To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.
try to replace
newStr[i] = ltr.toUpperCase();
to
newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);
So the result will be [ Gap , gAp , gaP ]
Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

Flutter/Dart: Split string by first occurrence

Is there a way to split a string by some symbol but only at first occurrence?
Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'
string.split(':');
I tried using the split() method. But it doesn't have a limit attribute or something like that.
You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:
String s = "date : '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
You can split the string, skip the first item of the list created and re-join them to a string.
In your case it would be something like:
var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim(); // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"
The trim methods remove any unneccessary whitespaces around the first colon.
Just use the split method on the string. It accepts a delimiter/separator/pattern to split the text by. It returns a list of values separated by the provided delimiter/separator/pattern.
Usage:
const str = 'date: 2019:04:01';
final values = string.split(': '); // Notice the whitespace after colon
Output:
Inspired by python, I've wrote this utility function to support string split with an optionally maximum number of splits. Usage:
split("a=b=c", "="); // ["a", "b", "c"]
split("a=b=c", "=", max: 1); // ["a", "b=c"]
split("",""); // [""] (edge case where separator is empty)
split("a=", "="); // ["a", ""]
split("=", "="); // ["", ""]
split("date: '2019:04:01'", ":", max: 1) // ["date", " '2019:04:01'"] (as asked in question)
Define this function in your code:
List<String> split(String string, String separator, {int max = 0}) {
var result = List<String>();
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
string = string.substring(index + separator.length);
}
return result;
}
Online demo: https://dartpad.dev/e9a5a8a5ff803092c76a26d6721bfaf4
I found that very simple by removing the first item and "join" the rest of the List
String date = "date:'2019:04:01'";
List<String> dateParts = date.split(":");
List<String> wantedParts = [dateParts.removeAt(0),dateParts.join(":")];
Use RegExp
string.split(RegExp(r":\s*(?=')"));
Note the use of a raw string (a string prefixed with r)
\s* matches zero or more whitespace character
(?=') matches ' without including itself
You can use extensions and use this one for separating text for the RichText/TextSpan use cases:
extension StringExtension on String {
List<String> controlledSplit(
String separator, {
int max = 1,
bool includeSeparator = false,
}) {
String string = this;
List<String> result = [];
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
print(index);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
if (includeSeparator) {
result.add(separator);
}
string = string.substring(index + separator.length);
}
return result;
}
}
Then you can just reference this as a method for any string through that extension:
void main() {
String mainString = 'Here was john and john was here';
print(mainString.controlledSplit('john', max:1, includeSeparator:true));
}
Just convert list to string and search
productModel.tagsList.toString().contains(filterText.toLowerCase())

What is the best way to trim a trailing character in Dart?

In Dart the trim(), trimLeft() and trimRight() string methods do not take a parameter to specify unwanted non-whitespace characters.
What is the best way to trim a specific character from the ends of a string in Dart?
I am using this for now, but it feels hard to remember and not very generic:
final trailing = RegExp(r"/+$");
final trimmed = "test///".replaceAll(trailing, "");
assert(trimmed == "test");
There is no specific functionality to trim non-whitespace from the end of a string.
Your RegExp based approach is reasonable, but can be dangerous when the character you want to remove is meaningful in a RegExp.
I'd just make my own function:
String removeTrailing(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = from.length;
while (from.startsWith(pattern, i - pattern.length)) i -= pattern.length;
return from.substring(0, i);
}
Then you can use it as:
final trimmed = removeTrailing("/", "test///")
assert(trimmed == "test");
The corresponding trimLeading function would be:
String trimLeading(String pattern, String from) {
if (pattern.isEmpty) return from;
var i = 0;
while (from.startsWith(pattern, i)) i += pattern.length;
return from.substring(i);
}
Since the existing answer by lrn has a lot of problems - including infinite loop scenarios - I thought I'd post my version.
String trimLeft(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.startsWith(pattern) ){
from = from.substring(pattern.length);
}
return from;
}
String trimRight(String from, String pattern){
if( (from??'').isEmpty || (pattern??'').isEmpty || pattern.length>from.length ) return from;
while( from.endsWith(pattern) ){
from = from.substring(0, from.length-pattern.length);
}
return from;
}
String trim(String from, String pattern){
return trimLeft(trimRight(from, pattern), pattern);
}
To trim all trailing/right characters by specified characters, use the method:
class StringUtil {
static String trimLastCharacters(String srcStr, String pattern) {
if (srcStr.length > 0) {
if (srcStr.endsWith(pattern)) {
final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
return trimLastCharacters(v, pattern);
}
return srcStr;
}
return srcStr;
}
}
For example, you want to remove all 0 behind the decimals
$23.67890000
then, invoke the method
StringUtil.trimLastCharacters("$23.67890000", "0")
finally, got the output:
$23.6789

(DOORS/DXL) Script for Split Object text in some atributtes using Tab

I'm using for for a year but now I have to modify small scripts and I'm a newbie with DXL. I have searched in before questions but I don't know how I can do it.
I have to develope a script that analyzes all objects in the same formal module to extract from each "object text" different strings separated by tab, to be written in other different attributes of the same object.
The formal module contents has been imported from Word. In that way that normal text format is defined as "object text" and every Title style is associated to a given level heading. In that way each object is provided with object heading or object text (but not both at the same time). Objects with object heading doesn't require any further action. However for objects provided with object text, I have to extract from object text some atributes separated by tabs.
For example a typical object text could be:
NNNN TEXT/TABLE/OLE OBJECT/ANY OTHER STRING (XXXXXX) (YYYYYY)
After apply the script it should be converted as:
Attribute 1: NNNN
Object Text: TEXT/TABLE/OLE OBJECT/ANY OTHER STRING
Attribute 2: XXXXXX
Attribute 3: YYYYYY
I have small script as example but I have passed all the morning trying to modify it to get I need but I can't do it:
Object o = current
//bool get_text(Object o) {return o."Object Heading" "" != ""}
string get_text(Object o)
{
if (o."Object Heading" "" != "")
return "Object Heading"
else
return "Object Text"
}
Regexp r_id = regexp "(http://0-9a-z/.+) "
for o in current Module do
{
string texto = o.(get_text(o))
if (r_id text)
{
o."Attribute 1" = textmatch 1
string input = richTextWithOle(o.(get_text(o)))
string output = cutRichText(input, 0, length(textmatch 1))
o.(get_text(o)) = richText(output)
}
}
This was a complicated one, but I think I have it figured out. Thanks for posting this because I may find it useful in the future as well.
I tried this out and it seems to work:
Object o
string get_text(Object o)
{
if (o."Object Heading" "" != "")
return "Object Heading"
else
return "Object Text"
}
char cTab = '\t' //The tab character to find
Buffer b = create
string tmp = "" //Needed to concatenate buffer parts
int offset = 0
for o in current Module do
{
string attr = get_text(o)
b = o.attr //Put the contents in the buffer
offset = contains(b, cTab) //Find the first tab
o."Attribute 1" = b[0:offset-1] //Set the first Attribute
b = b[offset+1:] //Remove the first attribute from the text
offset = contains(b, cTab)
if(offset > -1)
{
if(attr == "Object Heading") o.attr = b[0:offset-1]
b = b[offset+1:]
offset = contains(b, cTab)
if(offset > -1)
{
o."Attribute 2" = b[1:offset-2] //Set the second Attribute without the ()
b = b[offset+1:]
o."Attribute 3" = b[1:length(b)-2] //Set the third Attribute without the ()
} else {
o."Attribute 2" = b[1:length(b)-2] //Set the second Attribute without the ()
}
} else {
if(attr == "Object Heading") o.attr = b[0:]
}
if(attr == "Object Text")
{
b = richTextWithOle(o.attr) "" //This section removes the attributes from the contents without losing the rich text formatting and OLEs that may be present.
string word = o."Attribute 1"
offset = contains(b, word, 0)
tmp = b[0:offset-1] "" b[(offset+length(word)+5):]
b = tmp
word = "(" o."Attribute 2" ")"
offset = contains(b, word, 0)
if(offset > -1)
{
tmp = b[0:offset-6] "" b[offset+length(word):]
b = tmp
}
word = "(" o."Attribute 3" ")"
offset = contains(b, word, 0)
if(offset > -1)
{
tmp = b[0:offset-6] "" b[offset+length(word):]
}
o.attr = richText(tmp) //Set the Object Text or Heading
}
}
delete b //Release the buffer resources
Let me know if this gives you any trouble or if you want more detailed explination of the code.
EDIT: I updated the above code to take care of the issues you mentioned. It should be all set now. Let me know if you have any more trouble with it.

Entity Framework 4: Generic return type for a method

I have the following code -
var db = new DBEntities();
var entity = //get entity;
lblName.Text = string.Empty;
var names = entity.Names.OrderBy(x => x.Value).ToList();
for (var i = 0; i < names .Count; i++)
{
if (i == names .Count - 1) lblName.Text += names [i].Value + ".";
else lblName.Text += names [i].Value + ", ";
}
I'll have several For loops like above which will format the value to be displayed in a label. I'm trying to make a method out of it which will do the formatting when I pass in the collection and the label, something like -
void FormatValue(List<??> items, Label label)
{
//For loop
//Format value
}
What do I pass in for the List. How do I make this generic enough so I'll be able to use it for all entity.Names, entity.Xxx, entity.Yyy etc?
Make the method itself generic and allow the caller to specify a formatter:
void FormatValue<T>(List<T> items, Label label, Func<string, T> formatter)
{
foreach(var item in items)
{
label.Text += formatter(item);
}
}
You can then call the method like:
FormatValue<Name>(entity.Names.OrderBy(x => x.Value).ToList(),
lblName,
i => i.Value + ", ");

Resources