我使用 <pre>
显示以下多行字符串如下所示,其中每行都使用换行符表示:
SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem
我想解析build:e9kem
出,并且每次多行的内容都会有所不同。但它会有build:
在每一个。
我尝试过:
const regexp = /^build:(.*)$/m;
//stringPar would vary every time
const stringPar = `SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem`;
尝试像这样显示它:
{stringPar.match(regexp)[1])};
它解析正确,但对于某些多行字符串,它返回 Uncaught TypeError: Cannot read property '1' of null
当我尝试显示诸如 stringPar.match(regexp)[1]
之类的字符串时,但当控制台像 console.log(stringPar.match(regexp)[1]) 这样进行控制台记录时,它会正确记录字符串。
可能是什么问题?
提前感谢您,并将投票/接受答案
编辑(在 ReactJS 中)
它基本上是一个一遍又一遍地渲染的组件, Prop 被传递到其中。
export default class tableRow extends Component {
...
render() {
console.log(this.props.stringPar.match(regexp)[1]);
return (
<tr>
<td>
{/*Even tried {this.props.stringPar.match(regexp)[1]==null? " ": this.props.stringPar.match(regexp)} but still getting the same error*/}
<button>{this.props.stringPar.match(regexp)[1]}</button>
<td>
<tr>
)
}
}
最佳答案
What could possibly be the issue?
正则表达式并非在所有情况下都匹配,可能是因为:
every time the content of the multi-line will vary
执行类似的操作,以便您可以看到字符串不匹配时的样子:
export default class tableRow extends Component {
...
render() {
// ensure we actually have a string to run match on so don't get an error
const matchStr = this.props.stringPar || '';
const m = matchStr.match(regexp); // run match
const matchFound = m && m.length > 0; // boolean, was match found
const build = matchFound ? m[1] : 'build fallback'; // regex match or fallback if no match was found
if (!matchFound) {
console.log("Could not find 'build:' in:", matchStr, matchStr.length === 0 ? 'BLANK!' : 'NOT BLANK');
}
return (
<tr>
<td>
<button>{build}</button>
<td>
<tr>
)
}
}
并相应地调整您的正则表达式。
关于Javascript + ReactJS : Why doesn't regex . match() 返回不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623246/