Я не верю, что это проблема спасения символа, как указано здесь. Regexp с .exec не работает
Что я пытаюсь сделать? /> В чем проблема? : шаблон режима будет работать с: const reg = '[a-za-z0-9. \\\\ s]+'; и правильно подтверждает вводу моей формы. Однако, пытаясь извлечь каждый отдельный матч, я сталкиваюсь с проблемами. Похоже, есть 2 способа извлечения совпадений из объекта корпорации, и я попытался, чтобы оба описали MDN DOC. При попытке использовать буквальный или объект REGEXP с этим шаблоном и функцию .exex () я либо получаю ошибки, либо не соответствует правильному сопоставлению шаблона. Даже когда я получил один шаблон для почти работы, он вернул бы null .
Что я сделал для отладки? : Я пробовал каждую комбинацию струн, литералов и комбинаций конструкторов, о которых я могу думать, и ничто не работает. Я попытался утешить журнал и пытаться каждый метод в соответствии с MDN, и ничего не работает. Я старался убедиться, что я также использую правильный уход персонажа. Причина, по которой у меня есть моя режима в струне вместо буквальной, заключается в том, что по какой -то причине она неверно отображается в HTML. Когда я использую единственный шаблон регуляции в строках, который, по -видимому, работает, он отображается в моем HTML по -разному, и я проверил, используя Expect Element. Спасибо. My REGEXP, которую я пытался, и другой код прокомментируется с примечаниями.
Код: Выделить всё
import ChatBot from './ChatBot';
const ChatBotCard = (props) => {
//Works but is a string and not a literal?
const reg = '[a-zA-Z0-9.\\\\s]+';
//Not working
//const reg = /[a-zA-Z0-9.\\s]+/;
//const reg = new RegExp('[a-zA-Z0-9.\\\\s]+', 'gm');
//const regexp ='[a-zA-Z0-9.\\\\s]+';
//const reg = new RegExp( regexp );
//const reg = new RegExp(/[a-zA-Z0-9.\\s]+/);
//const reg = new RegExp("[a-zA-Z0-9.\\s]+");
const [chatBotStatus, setChatBotStatus] = useState(false)
const [userInput, setUserInput] = useState('')
const [toggle, setToggle] = useState(false)
const [errmssg, setErrmssg] = useState('');
const formHandle = (e) => {
e.preventDefault();
let input = document.forms["botForm"]["formInput"].value;
// Attempt 1:
// Will not work for just string its not an object
// Gives TypeError : reg.exec is not a function
// let result = reg.exec(x);
// Attempt 2:
// So we need to use RegExp to use exec() method instead
// I can not get the RegExp to render right in the HTML.
// I think the / before and after is being rendered with it
// This makes the expression invalid and exec() will return null ?
// Exec: Executes a search for a match in a string. It returns an array of information or null on a mismatch.
/* let result;
if((result = reg.exec(input)) == null)
{
console.log('Result array is null');
console.log('Result: '+ result);
}
while ((result = reg.exec(input)) !== null) {
let msg = 'Found a match ' + result[0] + '. ';
msg += 'Next match starts at ' + reg.lastIndex;
console.log(msg);
console.log('Result array is not null');
console.log('Result: '+ result);
} */
// Attempt 3:
// This also did not work but according to MDN
// You can also use exec() without creating a RegExp object explicitly:
// This also does not seem to work as expected
//let result = /[a-zA-Z0-9.\\s]+/.exec(input);
console.log("Form handle: input: " + input);
console.log("Reg exp: " + reg);
//console.log("Result is: " + result);
// Additional error handling ( does not matter for regex )
if ( input.length > 126)
{
setErrmssg('Shorten your question');
setTimeout(() => {
setErrmssg('');
}, 3000);
return false;
}
if ( input.length {
setErrmssg('');
}, 3000);
return false;
}
//Set data to call api
setUserInput(input);
setToggle(true);
}
return (
style={{
backgroundColor: '#1B2524ff',
border: '1px solid #212C50ff',
height: '100%',
}}
>
{props.message}
{errmssg}
{"You asked about : " + userInput}
)
};
export default ChatBotCard
Плохой вывод:
Подробнее здесь: https://stackoverflow.com/questions/729 ... ot-working